Reputation: 5826
I have a little "blackjack" program coded in C++. The thing is that the program asks questions like "Would you like... (y/n)?" where user needs to type y/n. I want to check if the value returned is actually the type that I want. So function that should return int, returns int and function that should return char, returns char, before it actually returns something.
I would need some suggestions guys. I think it's not that difficult, I just can't find any solution. Thank you.
Code:
char pickCard(){
char aCard;
std::cout << "Would you like another card?";
std::cin >> aCard;
if (aCard is a char){
return aChar;
} else {
std::cout << "Not a char!";
}
}
Upvotes: 2
Views: 1770
Reputation: 2537
If you want to force y or n as only allowed characters you can do:
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
}
you can use length() property of std::string to find its length. a string of length one is a char in most cases.
Upvotes: 0
Reputation: 1311
I guess you just want to know if the input string is in number format. >>
will set the istream
's failbit if it cannot convert the input string to 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."
}
Upvotes: 0
Reputation: 30559
I think you have a misconception of exactly how std::istream
's formatted input works. In your example, aCard
must be a char
, because you've declared it as such. If the use enters more than one character, one character will be put into aCard
, and std::cin
will hold onto the other characters and give them to you the next time you call operator>>
(or any other input function); if the user enters a number, aCard
will be the character representation of the first digit of that number.
Keep in mind that operator>>
knows what type of variable you've given it, and it will ensure that the user's input is valid for that type. If you give it an int
, it will make sure the users input is convertible to an int
or give you 0
if it isn't. A variable can never be anything but the type you declared it to be.
If you're interested in char
s in particular, there's a whole bunch of character classification functions you can use to tell what sort of character (letter, digit, whitespace, etc.) you're working with, but keep in mind that char foo('4')
is entirely different than int foo(4)
.
Upvotes: 2