How to use cin with unknown input types?

前端 未结 2 1676
清歌不尽
清歌不尽 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 <regex>
    #include <iostream>
    #include <string>
    #include <utility>
    
    
    using namespace std;
    
    int main() {
       regex pattern(R"(\s*(-?\d+)\s+(-?\d+)\s*|\s*([[:alpha:]])\s*)");
    
       string input;
       smatch match;
    
       char a_char;
       pair<int, int> 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])};
             }
          }
       }
    }
    
    0 讨论(0)
  • 2021-01-22 22:43

    Use std::getline to read the input into a string, then use std::istringstream to parse the values out.

    0 讨论(0)
提交回复
热议问题