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

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

    Few minor differences to πάντα ῥεῖ's answer - makes it also handle e.g. negative number representations etc., as well as being - IMHO - a little simpler to read.

    #include 
    #include 
    #include 
    
    int main()
    {
        std::istringstream iss("2.832 1.3067 nana1.678 x-1E2 xxx.05 meh.ugh");
        double num = 0;
        for (; iss; )
            if (iss >> num)
                std::cout << num << '\n';
            else if (!iss.eof())
            {
                iss.clear();
                iss.ignore(1);
            }
    }
    

    Output:

    2.832
    1.3067
    1.678
    -100
    0.05
    

    (see it running here)

提交回复
热议问题