How to test whether stringstream operator>> has parsed a bad type and skip it

前端 未结 5 2098
误落风尘
误落风尘 2020-11-21 06:49

I am interested in discussing methods for using stringstream to parse a line with multiple types. I would begin by looking at the following line:



        
5条回答
  •  被撕碎了的回忆
    2020-11-21 07:41

    The following code works well to skip the bad word and collect the valid double values

    istringstream iss("2.832 1.3067 nana 1.678");
    double num = 0;
    while(iss >> num || !iss.eof()) {
        if(iss.fail()) {
            iss.clear();
            string dummy;
            iss >> dummy;
            continue;
        }
        cout << num << endl;
    }
    

    Here's a fully working sample.


    Your sample almost got it right, it was just missing to consume the invalid input field from the stream after detecting it's wrong format

     if (parser.fail()) {
         std::cout << "Failed!" << std::endl;
         parser.clear();
         string dummy;
         parser >> dummy;
     }
    

    In your case the extraction will try to read again from "nana" for the last iteration, hence the last two lines in the output.

    Also note the trickery about iostream::fail() and how to actually test for iostream::eof() in my 1st sample. There's a well known Q&A, why simple testing for EOF as a loop condition is considered wrong. And it answers well, how to break the input loop when unexpected/invalid values were encountered. But just how to skip/ignore invalid input fields isn't explained there (and wasn't asked for).

提交回复
热议问题