I am a beginner in C++, just want to know why I cannot show the 6.9 in the second line of my output?
Does it seem like I ignore the word 'lady' and then just break the getline while loop and then move to the other line?
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream input("Text.txt");
ofstream output("Text1.txt");
string line;
while (getline(input, line)) {
istringstream inputstring(line);
double result;
string garbage;
while (inputstring >> garbage) {
inputstring.ignore();
if (inputstring >> result) {
output << result << endl;
}
}
}
}
This is my content of text.txt
broccoli 2.95
lady finger 6.9
Watermelon 10
Apple 7.8
Orangw 8.5
And this is the output
2.95
10
7.8
8.5
First you read "lady" into
garbage, then youignorethe single space character following it, then you try to read "finger" intoresult, which fails and the stream enters an error state.Then the loop exits, because the stream is in error.
You need to clear the error state when the number input fails, and you don't need to
ignoreanything.