Problem of using cin twice

前端 未结 6 1030
攒了一身酷
攒了一身酷 2020-12-01 13:27

Here is the code:

string str;
cin>>str;
cout<<\"first input:\"<

        
6条回答
  •  一整个雨季
    2020-12-01 13:52

    Also was searching for most suitable solution. Implementation of this operator could produce problems. And not always is acceptable to read entire line, or not mix different types in one input line.

    To solve problem, when you want to read some data from cin, and don't know if whitespaces was correctly extracted after last input operation, you can do like this:

    std::string str;
    std::cin >> std::ws >> str;
    

    But you can't use this to clear trailing newline symbol after last input operation from cin to do not affect new input, because std::ws will consume all whitespaces and will not return control until first non-ws character or EOF will be found, so pressing enter will not finish input process. In this case should be used

     std::cin.ignore( std::numeric_limits::max(), '\n' );
    

    which is more flexible.

    P.S. If got errors with max() function such as "identifier expected", it could be caused by max macros defined in some header (for example, by Microsoft); this could be fixed by using

     #undef max
    

提交回复
热议问题