我有一个C++程序需要接受用户输入。用户输入可以是两个整数(例如:1 3),也可以是字符(例如:s)。
我知道我可以得到这样的二元整数:
cin >> x >> y;
但是,如果输入字符,我该如何获取 cin 的值?我知道 cin.fail() 将被调用,但当我调用 cin.get() 时,它不会检索输入的字符。
感谢您的帮助!
std::getline
将输入读入字符串,然后使用 std::istringstream
解析出的值。
你可以在 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])};
}
}
}
}