我有一個C++程序需要用戶輸入。用戶輸入可以是兩個整數(例如:1 3),也可以是char(例如:s)。如何使用未知輸入類型的cin?
我知道我能得到三三兩兩整數這樣的:
cin >> x >> y;
但我如何去獲得CIN的值,如果一個字符輸入呢?我知道cin.fail()會被調用,但當我調用cin.get()時,它不會檢索輸入的字符。
感謝您的幫助!
我有一個C++程序需要用戶輸入。用戶輸入可以是兩個整數(例如:1 3),也可以是char(例如:s)。如何使用未知輸入類型的cin?
我知道我能得到三三兩兩整數這樣的:
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])};
}
}
}
}
如果整數可能是負數,這是行不通的。 – paddy
使用'模板'http://www.cplusplus.com/doc/tutorial/templates/ – UDB