【问题标题】:Split up a line coming in from a file. (part needs to include whitespace) c++分割来自文件的一行。 (部分需要包含空格) C++
【发布时间】:2017-04-16 04:04:44
【问题描述】:

我需要拆分来自文件的一行。该文件包含带有 ID、作者、出版日期和标题的书籍列表。

91507 刘易斯卡罗尔 1865 年爱丽丝梦游仙境

作者名我可以分为名字和名字,但是标题呢?我不知道该如何处理。我应该只创建第二个文件以便可以使用 getline 吗?

我是一个新手,我不明白如何为此使用 stringsteam,或者 split() 或类似的东西,所以如果这是你的建议,你能解释一下发生了什么吗?我还没有完全理解我看过的任何示例,无法修改它们以适合我的目的。

【问题讨论】:

    标签: c++ file parsing split getline


    【解决方案1】:
    ifstream fin;
    fin.open(filename)
    string id;
    string first;
    string last;
    string year;
    string title;
    if(fin.is_open())
    {
        while(!fin.eof())
        {
          fin >> id >> first >> last >> year;
          getline(fin, title);
          cout << first << " " << last << " " << title << endl;
        }
       fin.close();
    }
    

    【讨论】:

    • 你能解释一下while(!fin.eof())吗?我需要在我的程序中尝试一下,然后我会标记为已回答,但我通常会说 while (fin >> id >> first >> last >> year >> title );或类似的东西。当文件到达末尾时,while 循环失败并停止,对吗?那么 .eof() 是如何工作的呢?它是内置函数吗?
    • while(!fin.eof()) eof- 代表文件结束。 !fin.eof() = true 因为如果 eofbit 标志未设置,eof() 将返回 false。当循环尝试越过文件末尾时,设置了 eofbit 标志 eof() 在设置标志时返回 true
    • 你的方法也行。我刚刚习惯了使用 !fin.eof()。 eof() 是继承自 ios (cplusplus.com/reference/fstream/ifstream) 的 库的公共成员函数
    • 太棒了!经过我的努力,简直不敢相信它是如此简单!还有一个问题——为什么要使用 if 语句? if(fin.is_open())
    • 我这样做是因为如果文件没有成功打开并且如果你没有 is_open 那么你会有更多的错误。你也必须为 ofstream 这样做。不要忘记 .close() 它,因为如果你让文件保持打开状态,那么文件可能会损坏。
    【解决方案2】:

    这样做:

    #include <fstream>
    using namespace std;
    
    int main()
    {
        ifstream fin("somefile.txt");
        string id = "";
        string authFirst = "";
        string authLast = "";
        string date = "";
        string title = "";
        string temp = "";
        fin >> id >> authFirst >> authLast >> date >> title;
        getline(fin, temp);
    
        title += temp;
    
        cout << title << endl;
        return 0;
    }
    

    【讨论】:

    • 看了我的帖子后发现你甚至不需要在fin系列的末尾输入title;您可以让下一行的 getline 函数为您处理标题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多