[英]Duplicated data while extracting from a file in C++
我想在单个变量中提取文件行的每个单词。
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(int argc,char*argv[]){
ifstream myfile;
myfile.open("position.txt",ios::in);
string line;
while(getline(myfile,line)){
stringstream linestream(line);
string id;
int idNumber,posX,posY,frameNum;
linestream >> std::skipws;
linestream >> id >> idNumber >> posX >> posY >> frameNum;
cout << "idNumber" << idNumber << endl;
cout << "posX" << posX << endl;
cout << "posY" << posY << endl;
cout << "frameNum" << frameNum << "\n \n";
}
myfile.close();
return 0;
}
position.txt:
id: 1 263 138 0
id: 2 3 53 41
id: 3 3 40 112
id: 3 37 40 129
但是我得到这样的输出,变量重复了两次:
idNumber1
posX263
posY138
frameNum0
idNumber1
posX263
posY138
frameNum0
idNumber2
posX3
posY53
frameNum41
idNumber2
posX3
posY53
frameNum41
我不明白我的程序出了什么问题,有人可以告诉我该错误吗?
在position.txt
中的每个数据中都有空行,因此,当getline()
读取空行时,行linestream >> id >> idNumber >> posX >> posY >> frameNum;
将失败,并且将打印默认初始化的局部变量的不确定值。 在某些环境中,它们的内存分配在堆栈中的某个位置,并且值可能恰好被保留。 这就是为什么显示重复数据的原因。
从文件中删除空白行以读取或添加代码以跳过不包含此类数据的行:
if (!(linestream >> std::skipws) ||
!(linestream >> id >> idNumber >> posX >> posY >> frameNum)) continue;
代替
linestream >> std::skipws;
linestream >> id >> idNumber >> posX >> posY >> frameNum;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.