使用 fstream 从文本文件中读取数据

Reading Data from a text file with fstream

我在读取和使用数据文件时遇到了一些问题。我将从数据文件中创建 3 个类别。前两个类别均基于保证不会拆分的数据。第三类可能被拆分的次数不定。
下面的代码是我目前正在使用的过程。当每个段只是一个部分时(例如 segment3 = "dog"),这就完成了工作,但我需要应用程序能够处理 segment3 的可变数量的部分(例如 segment3 = "Golden Retriever" 或 "Half Golden Half Pug")。 segment1 和 segment2 保证是完整的,不会在空格之间分割。我明白为什么我的代码会跳过任何额外的空格(而不是记录 "Golden Retriever",它只会记录 "Golden"。我不知道如何操作我的代码,以便它理解之后行中的任何内容段 2 是段 3 的一部分。

 ______________________________
// This is the structure of the data file. It is a .txt
China 1987 Great Wall of China.
Jordan 1985 Petra.
Peru 1983 Machu Picchu. 
// End of Data file. Code below.
________________________________

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
    ifstream myFile("data.txt");
    string segment1;
    string segment2;
    string segment3;
    vector <string> myVec;

    while(myFile >> segment1 >> segment2 >> segment3)
    {
        vector <string> myVec; // 
        myVec.push_back(segment1); myVec.push_back(segment2); myVec.push_back(segment3); 
    int Value = atoi(myVec[1].c_str()); // should print int value prints zero with getline 
    }

    return 0;
}

我搜索了 Whosebug 和互联网,发现了一些想法,但似乎没有任何东西可以帮助解决我在使用代码时遇到的问题。 我最好的想法是放弃我目前阅读文件的方法。 1. 我可以使用 getline 将数据解析为向量。 2. 我可以将索引 0 分配给段 1,将索引 1 分配给段 2。 3. 我可以将索引 3 分配给段 3,直到向量的末尾。


Galik 的解决方案帮助我解决了这个问题,但现在我在尝试进行类型转换时遇到了问题。 [int altsegment2 = atoi(segment2.c_str());] 现在总是结果为零

您可以使用 std::getline 阅读整行的其余部分,如下所示:

#include <iostream>
#include <fstream>
#include <sstream> // testing
#include <vector>
using namespace std;

int main()
{
    // for testing I substituted this in place
    // of a file.
    std::istringstream myFile(R"~(
    China 1987 Great Wall of China.
    Jordan 1985 Petra.
    Peru 1983 Machu Picchu. 
    )~");

    string seg1;
    string seg2;
    string seg3;
    vector<string> v;

    // reads segments 1 & 2, skips spaces (std::ws), then take
    // the rest of the line into segment3
    while(std::getline(myFile >> seg1 >> seg2 >> std::ws, seg3))
    {
        v.push_back(seg1);
        v.push_back(seg2);
        v.push_back(seg3);
    }

    for(auto const& seg: v)
        std::cout << seg << '\n';

    return 0;
}

输出:

China
1987
Great Wall of China.
Jordan
1985
Petra.
Peru
1983
Machu Picchu.