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

前端 未结 5 2100
误落风尘
误落风尘 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:27

    I have built up a more fine tuned version for this, that is able to skip invalid input character wise (without need to separate double numbers with whitespace characters):

    #include 
    #include 
    #include 
    using namespace std;
    
    int main() {
    
        istringstream iss("2.832 1.3067 nana1.678 xxx.05 meh.ugh");
        double num = 0;
        while(iss >> num || !iss.eof()) {
            if(iss.fail()) {
                iss.clear();
                while(iss) {
                    char dummy = iss.peek();
                    if(std::isdigit(dummy) || dummy == '.') {
                        // Stop consuming invalid double characters
                        break;
                    }
                    else {
                        iss >> dummy; // Consume invalid double characters
                    }
                }
                continue;
            }
            cout << num << endl;
        }
        return 0;
    }
    

    Output

     2.832
     1.3067
     1.678
     0.05
    

    Live Demo

提交回复
热议问题