【问题标题】:Every other line of data is skipped when reading and storing data from a file从文件读取和存储数据时,每隔一行数据都会被跳过
【发布时间】:2013-04-11 02:08:44
【问题描述】:

我是 C++ 新手,在从文本文件中读取数据行时遇到了一些麻烦。假设我在文本文件中有未知数量的行,每一行的格式相同: int string double 。唯一可以确定的是空格将分隔给定行上的每条数据。我正在使用结构数组来存储数据。下面的代码效果很好,只是它在每个循环后跳过了一行输入。我尝试插入各种 ignore() 语句,但仍然无法让它读取每一行,只能读取隔行。如果我在最后重写了一些 getline 语句,那么在第一个循环之后开始为变量存储错误的数据。

文本文件可能如下所示:

18 JIMMY 71.5
32 TOM 68.25
27 SARAH 61.4


//code
struct PersonInfo
{
    int age;
    string name;
    double height;
};
//..... fstream inputFile; string input;

PersonInfo *people;
people = new PersonInfo[50];

int ix = 0;
getline(inputFile, input, ' ');
while(inputFile)
{
    people[ix].age = atoi(input.c_str());
    getline(inputFile, input, ' ');
    people[ix].name = input;    
    getline(inputFile, input, ' ');
    people[ix].height = atof(input.c_str());

    ix++;

    getline(inputFile, input, '\n');
    getline(inputFile, input, ' ');
}

我确信有更高级的方法可以做到这一点,但就像我说的那样,我对 C++ 还很陌生,所以如果对上面的代码稍作修改,那就太好了。谢谢!

【问题讨论】:

  • 我会阅读整行然后将行解析为 sep。字段。

标签: c++ file lines getline


【解决方案1】:

您可以按如下方式读取文件:

int ix = 0;
int age = 0;
string name ="";
double height = 0.0;
ifstream inputFile.open(input.c_str()); //input is input file name

while (inputFile>> age >> name >>  height)
{
  PersonInfo p ={age, name, height};
  people[ix++] = p;
}

【讨论】:

    【解决方案2】:

    你把整个代码弄得复杂得离谱。

    struct PersonInfo
    {
        int age;
        string name;
        double height;
    };
    
    std::vector<PersonInfo> people;
    PersonInfo newPerson;
    while(inputFile >> newPerson.age >> newPerson.name >> newPerson.height)
        people.push_back(std::move(newPerson));
    

    您的问题是因为首先您从文件中一次读取一个数据,然后从文件中读取一整行,然后再次从文件中一次读取一个数据。也许你的意图更像是这样?

    std::string fullline;
    while(std::getline(inputFile, fullline)) {
        std::stringstream linestream(fullline);
        std::getline(linestream, datawhatever);
        ....
    }
    

    顺便说一句,更惯用的代码可能看起来更像这样:

    std::istream& operator>>(std::istream& inputFile, PersonInfo& newPerson) 
    {return inputFile >> newPerson.age >> newPerson.name >> newPerson.height;}
    
    { //inside a function
        std::ifstream inputFile("filename.txt");
    
        typedef std::istream_iterator<PersonInfo> iit;
        std::vector<PersonInfo> people{iit(inputFile), iit()}; //read in
    }
    

    Proof it works here

    【讨论】:

    • 不幸的是我还没有了解字符串流,没有它这个问题是可以解决的。我相信我会学到很多东西,可以将我的代码简化为几行,但现在我几乎被我已经列出的内容所困扰。矢量解决方案看起来很有趣,所以我要试一试。
    • @DawgPwnd:如果你不熟悉 stringstream,那么第一段代码就是你要找的。​​span>
    猜你喜欢
    • 2013-11-30
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多