2016-05-05 32 views
0

我想提取單個變量中文件行的每個單詞。從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 

我不明白什麼是錯在我的程序,可以在任何有人告訴我這個錯誤嗎?

回答

0

有在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; 
+0

謝謝你,它工作得很好。 – para