【问题标题】:C++ reading strings from a file gives "-9.25596e+61"C++ 从文件中读取字符串给出“-9.25596e+61”
【发布时间】:2017-04-22 17:21:10
【问题描述】:

我正在尝试从文本文件中读取数据(效果不佳),它给了我非常奇怪的输出。我做了很多研究,我看不出有什么太明显的地方我做错了。

这是我要读取的文件:

Duck, Daffy
77.3
Pluto
88.0
Duck, Donald
94.3
Mouse, Mickey
80.0
Mouse, Minnie
94.3

这是我的功能:

int inputData(string names[], double averages[], int size)
{
    ifstream inputFile;

    inputFile.open("StudentData.txt");

    int count = 0;

    for (int i = 0; i < size; i++)
    {

        if (i == 0 || i % 2 == 0)
        {
            string name;
            inputFile >> name;
            cout << name;

            if (name.find(','))
            {
                inputFile >> name;
                cout << name;
            }
        }
        else
        {
            inputFile.ignore();
            inputFile >> averages[i];
            cout << endl <<  averages[i] << endl;
        }


        count++;

    }

    inputFile.close();

    return count / 2;
}

这是我尝试运行它时真正奇怪的输出:

Duck,Daffy
77.3
Pluto88.0
-9.25596e+61

-9.25596e+61

-9.25596e+61

-9.25596e+61

【问题讨论】:

  • 从输出中,很明显您已经将88.0 读作 Pluto 的名字。阅读string::find 的文档并查看它返回的内容。 (提示:这不是bool。)
  • @molbdnilo 你太棒了。我将其更改为if (name.find(',') != -1),现在可以使用了。提交您的评论作为答案,以便我接受?
  • if (i == 0 || i % 2 == 0) -- 测试可以简单写成if (i % 2 == 0)
  • @PaulMcKenzie 谢谢。
  • 问题已经得到解答,但我想你可能对 std::getline 感兴趣:en.cppreference.com/w/cpp/string/basic_string/getline

标签: c++ ifstream


【解决方案1】:

一个不会导致错误的错误是,第一个 if 应该只检查 i 是否为 0 mod 2,因为 0 也是 0 mod 2

您的错误在第二个if 中,它没有正确使用find

所以你想要的东西更像:

if (i % 2 == 0)
    {
        string name;
        inputFile >> name;
        cout << name;

        if (name.find(',') != string::npos)
        {    
            inputFile >> name;
            cout << name;
        }
        // ...

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多