My input file is:
2 5 <-- extra space at the end
4 <--extra space at the end
int main(){
ifstream input("input.txt");
istream& in = input;
string line1;
while( getline(in,line1)){
istringstream number1(line1);
while(number1.good()){
number1 >> temp1;
cout<<temp1<<endl;
}
}
input.close();
}
The problem is with the extra space at the end of the line my output is:
2
5
5
4
4
which is not what i want.. but if i remove the extra space it would work:
2
5
4
why is this happening? and how can i fix it so that even with extra spaces it reads the correct input?
Any help would be appreciated. Thanks!
The problem is with the
while (number1.good())loop. Thenumber1fail state will not be set until after thenumber1 >> temp1extraction fails, but you don’t test the fail state until the next time the loop condition is tested, which is after you print out the result of that extraction. You should change the inner loop to:This will extract the value, then test whether the extraction succeeded and will break out of the loop if the extraction fails, which is the behavior you want.