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

Data not being correctly read from input file

本文关键字:读取 数据 输入 文件      更新时间:2023-10-16

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

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

这其中可能的原因是什么?非常感谢!

 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>> 就会变得很痛苦,最好采用其他方法来解析基于流的输入。