C++ 使用cin,如何接受字符或整数作为输入?

C++ 使用cin,如何接受字符或整数作为输入?,c++,input,C++,Input,我正在编写一个程序,它接受一个卡片等级作为输入,然后将这些等级转换为它们所代表的值。所以一些例子包括A,5,10,K。我一直在想办法做到这一点 我想把它作为一个字符接受,然后把它转换,就像这样 char input = 0; std::cin >> input; if(input < 58 && input > 49) //accepting 2-9 { //convert integers } else if(input < 123 &&a

我正在编写一个程序,它接受一个卡片等级作为输入,然后将这些等级转换为它们所代表的值。所以一些例子包括A,5,10,K。我一直在想办法做到这一点

我想把它作为一个字符接受,然后把它转换,就像这样

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.
}

这就行了…不幸的是,除了10个。什么是有效的选项?

为什么不使用您现有的代码,并在第三个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的字符数组,因为我们不能在一个字符中存储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;
}

呵呵。我没有想到如果我得到1,那么只有一个选择。我唯一不喜欢的是,如果用户输入1,这应该被视为无效,它将被接受为10。不过我可能会这么做。@MichaelBlake just 1不一定要被接受。只需在接受零的语句中添加一个else。如果你没有得到零,抛出一个错误。谢谢。我没有考虑正则表达式,因为我没有第一手的经验。