How to use cin with unknown input types?

前端 未结 2 1685
清歌不尽
清歌不尽 2021-01-22 22:20

I have a C++ program which needs to take user input. The user input will either be two ints (for example: 1 3) or it will be a char (for example: s).

I know I can get th

2条回答
  •  遥遥无期
    2021-01-22 22:36

    You can do this in c++11. This solution is robust, will ignore spaces.

    This is compiled with clang++-libc++ in ubuntu 13.10. Note that gcc doesn't have a full regex implementation yet, but you could use Boost.Regex as an alternative.

    EDIT: Added negative numbers handling.

    #include 
    #include 
    #include 
    #include 
    
    
    using namespace std;
    
    int main() {
       regex pattern(R"(\s*(-?\d+)\s+(-?\d+)\s*|\s*([[:alpha:]])\s*)");
    
       string input;
       smatch match;
    
       char a_char;
       pair two_ints;
       while (getline(cin, input)) {
          if (regex_match(input, match, pattern)) {
             if (match[3].matched) {
                cout << match[3] << endl;
                a_char = match[3].str()[0];
             }
             else {
                cout << match[1] << " " << match[2] << endl;
                two_ints = {stoi(match[1]), stoi(match[2])};
             }
          }
       }
    }
    

提交回复
热议问题