I have a file which contains three integers per line. When I read the line I use a stringstream to separate the values, but it only reads the first value as it is. The other two are read as zero's.
ifstream inputstream(filename.c_str());
if( inputstream.is_open() ){
string line;
stringstream ss;
while( getline(inputstream, line) ){
//check line and extract elements
int id;
double income;
int members;
ss.clear();
ss.str(line);
ss >> id >> income >> members;*emphasized text*
}
}
In the case above, id is extracted correctly,开发者_如何转开发 but income, and members get assigned zero instead of the actual value.
EDIT: Solved
Never mind. The code works correctly. The error was in my print statement. I had a for loop printing the array at the same index every time.
Why don't you read directly from the file?
while( inputstream ) {
if( ! inputstream >> id ) ...
if( ! inputstream >> income ) ...
if( ! inputstream >> members ) ...
}
精彩评论