简体   繁体   中英

Duplicated data while extracting from a file in C++

I want to extract each word of a line of a file in a single variable.

#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

But I got in such output such variable duplicated twice:

    idNumber1
posX263
posY138
frameNum0

idNumber1
posX263
posY138
frameNum0

idNumber2
posX3
posY53
frameNum41

idNumber2
posX3
posY53
frameNum41

I don't understand what is wrong in my program,Can any one tell me about the mistake?

There are blank line in each data in position.txt , so when the blank lines are read by getline() , the reading in linestream >> id >> idNumber >> posX >> posY >> frameNum; will fail and indeterminate values of default-initialized local variables will be printed. In some environment, memory for them are allocated somewhere on the stack, and the values may happen to be preserved. That's why duplicate data are shown.

Remove the blank lines from the file to read or add code to skip lines that don't contain data like this:

if (!(linestream >> std::skipws) || 
    !(linestream >> id >> idNumber >> posX >> posY >> frameNum)) continue;

instead of

linestream >> std::skipws;
linestream >> id >> idNumber >> posX >> posY >> frameNum;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM