Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can std::cin fail to pass a user input in the command line to a variable with a type of char?

I have tried passing different inputs with the below code, but have failed to get the message printed: "Oops, you did not enter an ASCII char, let alone one that is y or n!" I have entered various Unicode characters which are not of char type (basically justed punching in ALT+random numbers, e.g. ™, š, ², Ž, ±. None of these produced the error. Does cin silently ignore or discard inputs that are not ASCII characters?

std::cout << "Would you like to play again? Enter y or n: ";
std::cin >> yOrN;
isChar = std::cin.fail();
//check if the user did not enter an ASCII char, e.g. test with a Unicode character
if (isChar)
{ 
    std::cout << "Oops, you did not enter an ASCII char, let alone one that is y or n!\n";
    std::cin.clear();
}

OS: Windows 10 64 bit, x64-based processor Compiler: Visual Studio Community 2015

I was not able to resolve this problem through searching for "extract a non-ASCII character cin C++" and looking at the first three pages.

I'm very new on Stack Overflow, so forgive me if I have violated any rules or code of conduct with this question. I'm learning C++ on learncpp.com and am writing my own code to answer question 2 of this page.

Update: I guess there is no reason for my program to validate whether a char is entered. However, I guess maybe I was so curious to know that I did not think too much about whether it was actually necessary for the program.

like image 677
James Ray Avatar asked Nov 08 '22 23:11

James Ray


1 Answers

std::cin.fail(); will return true if the underlying stream failed reading or writing data. it has nothing to do with the encoding you provide.

It is also worth mentioning that char is not really aware of utf-8 or ASCII, it's just a byte. neither does C++ streams validate the data's encoding.

So in this case, Ž (and others) is a valid input for std::cin.

If you want to validate ASCII only characters, you need to do it yourself:

std::cin >> c;
if (c < 0 || c > 127) { /*handle non ASCII chars*/  }

In your case, you need to validate against y or n:

std::cin >> c;
if (c != 'y' && c != 'n') { /*handle invalid input*/  }
like image 114
David Haim Avatar answered Nov 14 '22 21:11

David Haim