2

ユーザー入力を受け取る必要がある C++ プログラムがあります。ユーザー入力は、2 つの整数 (例: 1 3) または文字 (例: s) のいずれかになります。

私は次のように2つの整数を取得できることを知っています:

cin >> x >> y;

しかし、代わりに char が入力された場合、どうすれば cin の値を取得できますか? cin.fail() が呼び出されることはわかっていますが、cin.get() を呼び出すと、入力された文字が取得されません。

助けてくれてありがとう!

4

2 に答える 2

3

std::getline入力を文字列に読み込むために使用しstd::istringstream、値を解析するために使用します。

于 2013-10-31T04:29:00.253 に答える
1

これは c++11 で実行できます。このソリューションは堅牢で、スペースを無視します。

これは、ubuntu 13.10 の clang++-libc++ でコンパイルされます。gcc にはまだ完全な正規表現が実装されていませんが、代わりにBoost.Regexを使用できることに注意してください。

編集: 負の数の処理を追加しました。

#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])};
         }
      }
   }
}
于 2013-10-31T06:55:18.023 に答える