C plus plus不同类型的I/O副本txt文件
我正在学习如何使用c plus plus读取/写入文件,并遇到了复制txt文件第一行的问题。我粘贴下面的txt文件。正如你所看到的,第一行有两个字符串,而下面的行是不同的类型。我如何声明第2列的类型,因为它是第1行的一个字符串,之后是整数?虽然我可以通过将所有内容声明为字符串来将文件的内容复制到output.txt
,但我很好奇如何处理不同的类型。非常感谢您的帮助。C plus plus不同类型的I/O副本txt文件
input.txt
文件:
firstname value
Jack 1
Jacob 3
Jerry 2
Jeremy 3
Joseph 3
Jim 3
我正因为冲突类型的空白output.txt
文件,我认为。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string fname;
int value;
using namespace std;
int main() {
ifstream in_file; //variable name
in_file.open("input.txt");
if (in_file.fail()){
cout << " The file is not found " << endl;
return 1;
}
ofstream out_file;
out_file.open("output.txt");
while (in_file >> fname >> value){
out_file << fname << " " << value << endl;
};
}
感谢@ForceBru这为我工作,但请让我知道是否有做到这一点更有效的方式:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string fname;
string col2;
int lname;
using namespace std;
int main() {
int count=0;
ifstream in_file; //variable name
in_file.open("input.txt");
if (in_file.fail()){
cout << " The file is not found " << endl;
return 1;
}
ofstream out_file;
out_file.open("output.txt");
if (count==0){
in_file >> fname >> col2;
out_file << fname << " " << col2 << endl;
count++;
}
while (in_file >> fname >> lname){
out_file << fname << " " << lname << endl;
};
}
为什么你需要为第一行计数?你也不需要这些值,一个简单的getline就会跳过它们。 – 2017-06-04 18:01:02
计数是用于指定第一行的字符串值,我不知道如何实现getline – st4rgut
@st以及count如何知道,这是第一行?你应该使用getline,而不是实现它。 – 2017-06-07 09:17:52
刚刚处理的第一行以不同的方式,为两个字符串,不是一个字符串和一个int。 – ForceBru