【问题标题】:Having trouble with reading from file从文件读取时遇到问题
【发布时间】:2014-02-19 07:18:52
【问题描述】:

好的,所以我应该读取文件的整行,然后遍历并将每个部分单独分成正确的分组。这是我目前写的代码。

while(!inFile.getline(largeString, LINE_SIZE, '\n').eof() && count < TEAMS)
    {
        next = 0;
        next = buildStruct(largeString, smallString, next);
        strcpy(stats[count].name, smallString);
        cout << stats[count].name << endl;
        next = buildStruct(largeString, smallString, next);
        stats[count].wins = atoi(smallString);
        cout << stats[count].wins << endl;
        next = buildStruct(largeString, smallString, next);
        stats[count].losses = atoi(smallString);
        cout << stats[count].losses << endl;
        next = buildStruct(largeString, smallString, next);
        stats[count].overtime_losses = atoi(smallString);
        cout << stats[count].overtime_losses << endl;
        count++;
    }

这是我文件的内容

 Brookings  12   24    7

   Aberdeen     22    16 2

 Austin    28   11     1

  Bismark   24   13      4

    Minot  18    21     3

这是我从编译器得到的

Brookings
12
24
7

0
0
0
Aberdeen
22
16
2

我不知道零是从哪里来的……请帮忙

【问题讨论】:

  • 您的文本文件在每行数据后都有一个空白换行符。您似乎没有避免空白行
  • 看看stringstream,你会喜欢的。

标签: c++ file getline


【解决方案1】:

在进行处理之前,检查largeString是否为空。

while(!inFile.getline(largeString, LINE_SIZE, '\n').eof() && count < TEAMS)    
{
if(largeString && largeString[0] != '\0')
{
next = 0;
...
...
}
}

作为 Beta,建议您一定要研究一下字符串流。

【讨论】:

    猜你喜欢
    • 2015-02-19
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    相关资源
    最近更新 更多