How to extract mixed format using istringstream

后端 未结 4 694
独厮守ぢ
独厮守ぢ 2021-01-19 03:05

Why does my program not output:

10
1.546
,Apple 1

instead of

10
1

here\'s my program

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-19 03:53

    Allow me to suggest the following.

    I don't consider it 'smoother', as cin / cout dialogue is not 'smooth', imho.

    But I think this might be closer to what you want.

     int main (int, char**)
     {
        // always initialize your variables 
        // to value you would not expect from input        
        int            a = -99;
        double         b = 0.0;
        std::string    c("");
        char comma1 = 'Z';
        char comma2 = 'z';
    
        std::string str = "10,1.546,Apple 1";
        std::istringstream ss(str);
    
        ss >> a >> comma1 >> b >> comma2;
    
        // the last parameter has the default delimiter in it
        (void)getline(ss, c, '\n');  // to get past this default delimiter, 
                                     // specify a different delimiter
    
        std::cout << std::endl;
        std::cout << a << "   '" << comma1 <<  "'   " << std::endl;
        std::cout << b << "   '" << comma2 <<  "'   " << std::endl;
        std::cout << c << std::endl;
    
        return 0;
     }
    

    Results: (and, of course, you need not do anything with the commas.)

    10 ','
    1.546 ','
    Apple 1

提交回复
热议问题