[英]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.