未从输入文件中正确读取数据
Data not being correctly read from input file
>请参阅下面的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::istream
的 operator>>
不更新变量的最常见原因可以用下面的简单例子来演示:
#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>>
就会变得很痛苦,最好采用其他方法来解析基于流的输入。
相关文章:
- 如何在ros2中从rosbag2读取数据
- OpenCV 和从 OutputArrays 或 (Mat) 读取数据
- 使用C++从磁卡读卡器MT188读取数据
- HDF5 简单读取数据集失败
- 嵌套结构,从由空行分隔的文件中读取数据
- 不要从输入队列套接字读取数据
- 从文件中读取数据,操作员>>
- 如何从excel文件中读取数据并存储到变量中?
- C++:从文件中读取x y数据会产生无限循环吗
- 无法通过FT232RL读取数据
- 如何从QNetworkReply读取数据?
- C++ 逐行从文件(包含空格)读取数据
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 我们可以从 TXT 文件中读取数据并使用 C 和 C++ 将其保存到 SQL 数据库吗?
- 从多个 tcp 连接读取数据
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- Qt TCP服务器不从客户端读取数据
- 累积从 C++11 中的文件中读取数据的整数
- 从 txt 文件中读取数据的最简单方法
- 从 txt 文件中读取数据的 Getline