检查返回值是整数还是char

时间:2015-12-14 20:18:51

标签: c++

我有一个用C ++编码的“二十一点”程序。问题在于程序会问诸如“你想要......(是/否)?”之类的问题。用户需要键入y / n。我想检查返回的值是否实际上是我想要的类型。所以应该返回int的函数,返回int和应该返回char的函数,在实际返回之前返回char。

我需要一些建议。我认为这并不困难,我找不到任何解决方案。谢谢。

代码:

byte[] array = operator(thing);

3 个答案:

答案 0 :(得分:2)

我认为您对std::istream格式化输入的确切运作方式存在误解。在您的示例中,aCard 必须char,因为您已将其声明为此类。如果使用输入多个字符,则一个字符将被放入aCardstd::cin将保留其他字符,并在您下次拨打operator>>时将其提供给您(或任何其他输入功能);如果用户输入一个数字,aCard将是该数字的第一个数字的字符表示。

请记住,operator>>知道您给它的变量类型,并确保用户的输入对该类型有效。如果您为其提供int,则会确保用户输入可转换为int,或者如果不是,则会提供0。变量永远不会是你声明它的类型。

如果您对char特别感兴趣,可以使用一大堆character classification functions来判断您是什么类型的字符(字母,数字,空白等)使用,但请注意char foo('4')int foo(4)完全不同。

答案 1 :(得分:0)

如果您想强制y或n作为唯一允许的字符,您可以这样做:

char pickCard(){
    std::string response;
    std::cout << "Would you like another card?";
    std::cin >> response;
    if (response=="y" || response=="n"){

        return response[0]; //or anything useful 
    } else {
        std::cout << "Not a char!";
         //... more code here
    }
         //... more code here
}

你可以使用std :: string的length()属性来查找它的长度。在大多数情况下,长度为1的字符串是char。

答案 2 :(得分:0)

我想你只是想知道输入字符串是否为数字格式。 >>如果无法将输入字符串转换为istream,则会设置int的失败位。

int num;

if (cin >> num) {       // input is "123abc", num == 123
  cout <<  "yes, input is a number. At least start with some figures. "
  cout << "num == " << num;
} else { // input is "abc" , error
  cout << "no, input is not a number or there is some kind of IO error." 

} 
相关问题