Can std :: cin not pass user input on the command line to a variable of type char?

I tried passing different inputs with the code below, but did not receive the message: "Unfortunately, you did not enter an ASCII char, not to mention that it is y or n!" I entered various Unicode characters that are not char type (mostly fair stamping in random ALT + numbers, for example ™, š, ², Ž, ±. None of these errors caused an error. Sin silently ignores or discards the input data 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, eg 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 2015 community

I could not solve this problem by doing a search for “CIN C ++ character extraction without ASCII characters” and looking at the first three pages.

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

Update: I think there is no reason for my program to check if char is entered. However, I was probably so interested to know that I did not think too much about whether this was really necessary for the program.

+5
source share
1 answer

std::cin.fail(); will return true if the underlying thread could not read or write data. this has nothing to do with the encoding you provide.

It's also worth mentioning that char doesn't know about utf-8 or ASCII, it's just a byte. neither C ++ streams check the data encoding.

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

If you want to check only ASCII 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 check for y or n :

 std::cin >> c; if (c != 'y' && c != 'n') { /*handle invalid input*/ } 
+1
source

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


All Articles