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

Store string into a variable in next line of a file

我刚开始使用 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;
}

替换

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

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

因为

并进行深度解释

Why does std::getline() skip input after a formatted extraction?

std::getline 读取直到遇到定界符或文件结尾,这里是

之后的换行符
5 10 15\n
        ^
// 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;
}

否则,尽管您声称 "I can't use getline() for [the 1st line]",您实际上可以使用 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;
}