将字符串存储到文件下一行的变量中

Store string into a variable in next line of a file

本文关键字:一行 变量 存储 字符串 文件      更新时间:2023-10-16

我刚刚开始在C++的<fstream>库刷新自己,我正在尝试将文本文件的第一行存储到 3 个整数变量中,所有变量都用空格分割。文本文件的第二行有一个字符串,我正在尝试让我的字符串变量来存储它。但是,我不确定如何转到文件的下一行。该文件如下所示:

5 10 15
My name is Luke

我知道使用getline获取整行然后转到下一行,但我没有将第一行存储到一个变量中,而是将 3 行存储到 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;
}

替换

inFile >> x >> y >> z;
getline(inFile, name);

inFile >> x >> y >> z;
inFile.ignore();
getline(inFile, name);

因为

为什么在"cin"之后使用">

getline"时需要cin.ignore((,而多次使用"cin"时不需要?

并深入解释

为什么 std::getline(( 在格式化提取后跳过输入?

std::getline读取,直到遇到文件的分隔符或结尾,这里是紧随其后的换行符

5 10 15n
^
// you need to ignore this

您可以通过以下方式忽略它

inFile.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
getline(inFile, name);

您有以下几种选择:

您可以使用operator>>读取 3 个整数,然后ignore()ifstream直到跳过新行,然后您可以使用std::getline()读取第二行:

#include <iostream>
#include <string>
#include <fstream>
#include <limits>
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 << "n" << "My name is Luke";
outFile.close();
inFile.open("C:\Users\luked\Desktop\Test.txt");
inFile >> x >> y >> z;
infile.ignore(numeric_limits<streamsize>::max(), 'n');
getline(inFile, name);
cout << x  << " " << y << " " << z << " " << endl << name;
return 0;
}

否则,尽管您声称"我不能将 getline(( 用于 [第一行]",但您实际上可以使用std::getline()来读取第一行。 只需在之后使用std::istringstream从该行读取整数即可。 然后您可以使用std::getline()读取第二行:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream inFile;
ofstream outFile;
string line, name;
int x,y,z;
outFile.open("C:\Users\luked\Desktop\Test.txt");
outFile << 5 << " " << 10 << " " << 15 << "n" << "My name is Luke";
outFile.close();
inFile.open("C:\Users\luked\Desktop\Test.txt");
getline(inFile, line);
istringstream(line) >> x >> y >> z;
getline(inFile, name);
cout << x  << " " << y << " " << z << " " << endl << name;
return 0;
}