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

问题描述 投票:0回答:3

我刚刚开始在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;
}
c++ fstream
3个回答
0
投票

替换

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

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

因为

Why is cin.ignore() necessary when using "getline" after "cin", but is not required when using "cin" multiple times?


0
投票

[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;
}

否则,尽管您有什么想法,您实际上可以使用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;
}

0
投票

您有两种选择:

© www.soinside.com 2019 - 2024. All rights reserved.