我试图在C++中完成一个简单的初学者任务。我有一个包含一行“John Smith 31”文本的文件。我想使用ifstream变量读取这些数据。但是,我想将名称“John Smith”读入一个字符串变量,然后将数字“31”读入一个单独的整数变量。
我尝试使用getline函数,如下所示:
ifstream inFile;
string name;
int age;
inFile.open("file.txt");
getline(inFile, name);
inFile >> age;
cout << name << endl;
cout << age << endl;
inFile.close();
问题在于它会输出整行“John Smith 31”。有没有办法让getline函数在获取名称后停止,然后重新开始获取数字?而不需要操作输入文件呢?
getline
。这真的很简单。 - David Schwartz