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

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

    If you like concision - here's another option that (ab?)uses && to get cout done only when a number's been parsed successfully, and when a number isn't parsed it uses the comma operator to be able to clear() stream error state inside the conditional before reading a character to be ignored...

    #include 
    #include 
    #include 
    
    int main()
    {
        std::istringstream iss("2.832 1.3067 nana1.678 x-1E2 xxx.05 meh.ugh");
        double num = 0;
        char ignored;
        while (iss >> num && std::cout << num << '\n' ||
               (iss.clear(), iss) >> ignored)
            ;
    }
    

    http://ideone.com/WvtvfU

提交回复
热议问题