正确从 ifstream 获取值时出现问题

Problems getting values from ifstream correctly

本文关键字:问题 获取 ifstream      更新时间:2023-10-16
**EDIT:我通过将"inStream>> next"

更改为"inStream>> skipws>> next"来让它工作。 在我之前的一个函数(拉取姓氏和名字)中,我切换了noskipws。 显然,这种切换在功能之间持续?

我有一个程序,它是作业的一部分,应该读取一个格式设置为的文本文件:"姓氏名字 1 2 3 4 5 6 7 8 9 10"(其中 10 个数字中的每一个都是整数分数)。

我可以很好地读取姓氏和名字,但是当我开始阅读数字时,我只能读取第一个,然后其余的都设置为 0。

下面是应该读取分数的函数。 inStream已经取消了姓氏和名字。 我正在使用的文本文件有一行:

托西斯·哈雷 85 23 10 95 43 12 59 43 20 77

当运行程序并打印出 student.score 值从 0 到 9 时,第一个正确显示为"85",但所有重置都显示为"0"。 思潮?

void GetScores (ifstream& inStream, record& student)
{
    int score[10] = {-1, -1, -1, -1 ,-1 ,-1 ,-1 ,-1 ,-1 ,-1};
    int next;
    int counter = 0;
    string test;
    for (int i = 0; i < 10; i++)
    {
        inStream >> next;
        student.score[i] = next;
    }
}

假设输入确实是所有数字,该函数实际上应该可以工作。但是,应始终验证输入是否确实正确读取:

for (int i = 0; i != 10 && inStream >> next; ++i) {
    student.score[i] = next;
}
if (!inStream) {
    std::cout << "an input error occuredn";
}