【问题标题】:Can't get data from file in C++ [duplicate]无法从 C++ 中的文件中获取数据 [重复]
【发布时间】:2017-10-24 18:55:40
【问题描述】:

我一直在尝试使用循环读取文本文件。但由于某种原因,它似乎永远不会使整数值正确。我总是以垃圾值告终。

while(!file.eof())  // I've also tried other variations of this while loop, none of which worked either
    {
        // ifstream, string, char, string, int
        file >> name >> sex >> data >> score;  
        std::cout << name << std::endl;
        if (sex == 'F')
        {
            femaleAverage += score;
            femaleCount++;
        }
        else
        {
            maleAverage += score;
            maleCount++;
        }

        if (data.compare("CC"))
        {
            comAverage += score;
            comCount++;
        }
        else
        {
            uniAverage += score;
            uniCount++;
        }
    }

文本文件如下所示:

Bailey           M CC 68
Harrison         F CC 71
Grant            M UN 75
Peterson         F UN 69
Hsu              M UN 79
Bowles           M CC 75
Anderson         F UN 64
Nguyen           F CC 68
Sharp            F CC 75
Jones            M UN 75
McMillan         F UN 80
Gabriel          F UN 62 

【问题讨论】:

  • 你的输出是什么样的?

标签: c++ file text file-io text-files


【解决方案1】:

根据您的if 语句,看起来sex 被声明为char 而不是char*std::string。当您使用file &gt;&gt; sex 时,它会将文件中的下一个字符读入变量,不会像字符串或数字那样跳过空格。结果,sex 获得了名字后面的第一个空格,然后它将文件的性别字段读入data,并尝试将数据字段读入score

您可以在阅读之前使用std::skipws 值跳过空格。

您也不应该使用while (!file.feof()),请参阅Why is iostream::eof inside a loop condition considered wrong?

所以代码应该是这样的:

while (file >> name >> std::skipws >> sex >> data >> score) {
    std::cout << name << std::endl;
    if (sex == 'F')
    {
        femaleAverage += score;
        femaleCount++;
    }
    else
    {
        maleAverage += score;
        maleCount++;
    }

    if (data.compare("CC"))
    {
        comAverage += score;
        comCount++;
    }
    else
    {
        uniAverage += score;
        uniCount++;
    }
}

【讨论】:

  • 谢谢,你解决了一个问题。事实证明这不是导致我的问题的原因。不过,还是谢谢。
  • @ryan 出了什么问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-29
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多