【发布时间】:2020-01-17 19:24:44
【问题描述】:
我刚开始在 C++ 中的 <fstream> 库上刷新自己,我正在尝试将我的文本文件的第一行存储到 3 个整数变量中,所有变量都用空格分隔。文本文件的第二行有一个字符串,我试图让我的字符串变量来存储它。但是,我不确定如何转到文件的下一行。该文件如下所示:
5 10 15
My name is Luke
我知道使用 getline 获取整行然后转到下一行,但我没有将第一行存储到一个变量中,而是 3 所以我不能使用 getline()那个。这是我的代码。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream inFile;
ofstream outFile;
string name;
int x,y,z;
outFile.open("C:\\Users\\luked\\Desktop\\Test.txt");
outFile << 5 << " " << 10 << " " << 15 << endl << "My name is Luke";
outFile.close();
inFile.open("C:\\Users\\luked\\Desktop\\Test.txt");
inFile >> x >> y >> z;
getline(inFile, name);
cout << x << " " << y << " " << z << " " << endl << name;
return 0;
}
【问题讨论】: