Accept char input when should it be a string?

I am new to C ++ and am making a simple text RPG. Anyway, the scenario: I have a welcome screen with options 1-3, and you have a simple IF statement to check them here:

int choice;
std::cout << "--> ";
std::cin  >> choice;

if(choice == 1) {
//..

This works fine, but if someone enters a letter as a choice (instead of 1, 2 or 3), it will become “-392493492” or something else and the program will crash. So I came up with:

char choice;
std::cout << "--> ";
std::cin  >> choice;

if(choice == 1) {
//..

This works fine, but when I enter a number, it seems to completely skip IF statements. Is char "1" the same as number 1?

I get a compiler error with this (ISO-CPP or something else):

if(choice == "1")

So, how do I see if they entered 1-3 correctly ??

+3
source share
6 answers

, 1 '1' .

ASCII, , "1", : '1' 49.

"" C- (const char*), '' .

:

char choice = 0;
if (cin >> choice)  // check success
{
  switch(choice) // choose
  {
  case '1': {  /**/ break; }
  case '2': {  /**/ break; }
  case '3': {  /**/ break; }
  default:
    cout << choice
         << " is not a valid choice, please press 1, 2 or 3 and Enter"
         << endl;
  }
}

, , else-if .

+2
1 is an int
'1' is a char
"1" is a char array

, '1'.

+3

"-392493492" - , ( , ) , >> . , , :

if (std::cin >> choice) {
    switch (choice) {
    case 1: // ...
    case 2: // ...
    case 2: // ...
    default: // report error
    }
}
+3

if(choice == '1')

, ascii valyue 1 1, 49:

'1' == 49
+1

( char*, char), char:

if(choice == '1')

char '1' 1, 49 ( ASCII). ,

if(choice == 49)

In addition, you must have a branch elseto display an error message or something else, and prohibit the continuation of the program in case of input of an invalid input.

+1
source

the choice is char, so you should use '1' for validation. "1" represents a string with 1 character in it.

+1
source

Source: https://habr.com/ru/post/1744306/


All Articles