未从输入文件中正确读取数据

Data not being correctly read from input file

请看下面的c++函数。它的重点是将输入文件("is")中的变量存储到全局数组中。我通过调试器监视 "temp" 变量(第一个 if 语句似乎工作正常),在读取输入文件的第一行后,变量 temp 不再更新。

该文件采用特定格式,因此它应该读取一个 int,尽管我最终确实在 KEYFRAME if 语句的末尾放置了一个 char 以查看它是否正在读取结束符(不是) .

这有哪些可能的原因?非常感谢!

 void readFile(istream& is){
        string next;
        int j = 0;
        int i = 0;
    while (is){
    for (int i = 0; i < F; i++){ 
            is >> next;
            if (next == "OBJECT")
            {

                int num;
                is >> num;
                string name;
                is >> name;
                objects[j].objNum = num;
                objects[j].filename = name;
                j++;
            }
            else if (next == "KEYFRAME"){
                int k;
                int temp;
                is >> k;
                int time;
                is >> time;
                objects[k].myData[time].setObjNumber(k);
                objects[k].myData[time].setTime(time);
                is >> temp;
                objects[k].myData[time].setPosition('x', temp) ;
                is >> temp;
                objects[k].myData[time].setPosition('y', temp);
                is >> temp;
                objects[k].myData[time].setPosition('z', temp);
                is >> temp;
                objects[k].myData[time].setRotation('x', temp);
                is >> temp;
                objects[k].myData[time].setRotation('y', temp);
                is >> temp;
                objects[k].myData[time].setRotation('z', temp);
                is >> temp;
                objects[k].myData[time].setScaling('x', temp);
                is >> temp;
                objects[k].myData[time].setScaling('y', temp);
                is >> temp;
                objects[k].myData[time].setScaling('z', temp);
                char get;
                is >> get;
            }
            else {
                cout << "Error reading input file";
                return;
            }

        }
    }
}

std::istreamoperator>> 不更新变量的最常见原因可以使用以下简单示例进行说明:

#include <sstream>
#include <iostream>

int main() {

    std::string sample_input="1 2 3 A 4 5";

    std::istringstream i(sample_input);

    int a=0, b=0, c=0, d=0;
    std::string e;
    int f=0;

    i >> a >> b >> c >> d >> e >> f;

    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << c << std::endl;
    std::cout << d << std::endl;
    std::cout << e << std::endl;
    std::cout << f << std::endl;
}

这个程序的结果输出是:

    1
    2
    3
    0

    0

这个例子在第四个参数上强制转换错误。一旦 operator>> 遇到格式转换错误,就会在流中设置一个错误位,从而阻止进一步的转换。

使用 operator>> 时,有必要在 每次 输入格式转换后检查转换错误,并在必要时重置流的状态。

因此,您的答案是某处存在输入转换错误。我通常避免使用 operator>>。这适用于输入已知的简单情况,并且不存在错误输入的可能性。但是,一旦您遇到可能需要处理错误输入的情况,使用 operator>> 就会变得很痛苦,最好采用其他方法来解析基于流的输入。