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

时间:2016-02-08 04:34:07

标签: c++ 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.
}

这样可行......除了10个,不幸的是。什么是有效的选择?

3 个答案:

答案 0 :(得分:2)

为什么不使用你拥有的代码,只是在第三个if块中有一个特殊情况来处理10?

由于除了10以1开头之外没有有效输入,这应该非常简单:

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

答案 1 :(得分:2)

为什么不在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 :(得分:0)

我们应该使用大小为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;
}
相关问题