我正在学习如何使用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;
};
}
刚刚处理的第一行以不同的方式,为两个字符串,不是一个字符串和一个int。 – ForceBru