[英]Using cin, how can I accept a character or an integer as an input?
我正在編寫一個程序,該程序接受卡片等級作為輸入,然后將這些等級轉換為它們代表的值。 因此,一些示例包括A,5、10,K。我一直在嘗試找出實現此目的的方法。
我考慮過將其作為char
接受,然后將其轉換,就像這樣...
char input = 0;
std::cin >> input;
if(input < 58 && input > 49) //accepting 2-9
{
//convert integers
}
else if(input < 123 && input > 64)
{
//convert characters and check if they're valid.
}
那將起作用...不幸的是除了十個。 什么是可行的選擇?
為什么不使用第三個if塊中僅有的特殊情況的代碼來處理10個代碼呢?
由於除了以1開頭的10之外沒有有效輸入,因此這應該很簡單:
char input = 0;
std::cin >> input;
if(input < 58 && input > 49) //accepting 2-9
{
//convert integers
}
else if(input < 123 && input > 64)
{
//convert characters and check if they're valid.
}
else if(input == 49){ //accepts 1
std:cin >> input; //takes a second character
if(input == 48){ //this is 10
//do stuff for 10
}
else{
//throw error, 1 followed by anything but 0 is invalid input
}
}
為什么在2016年不使用std::regex
? @Michael Blake,是否需要手動執行解析?
我已經能夠達到預期的效果,如下所示:
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::regex regexp("[KQJA2-9]|(10)");
std::string in;
for (;;) {
std::cin >> in;
std::cout << (std::regex_match(in, regexp) ? "yes" : "no") << std::endl;
}
}
我們應該使用大小為2的char數組,因為我們不能在char中存儲10。 這是示例程序:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;
int main()
{
char s[2];
cin >> s;
if( (s[0] < 58 && s[0] > 48) && ( s[1] == '\0' || s[1] == 48) )
{
int m;
m = atoi(s);
cout << "integer " << m << endl;
}
else if(s[0] < 123 && s[0] > 64)
{
char c;
c = s[0];
cout << "char " << c << endl;
}
else
{
cout << "invalid input" << endl;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.