Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

c++ - Put a non-numeric input into an integer variable

I’m having a bit of a problem in C++. When I wrote this:

int a = ‘:‘;
cout << a;

This printed out 58. It checks out with the ASCII table.

But if I write this:

int a;
cin >> a;
//i type in “:”
cout << a;

This will print out 0. It seems like if I put in any non-numeric input, a will be 0. I expected it to print out the equivalent ASCII number.

Can someone explain this for me? Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're declaring a as an int, then the operator>> expects digits, but you give a punctuation, which makes extraction fails. As the result, since C++11, a is set to 0; before C++11 a won't be modified.

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set. (until C++11)

If extraction fails, zero is written to value and failbit is set. (since C++11)

And

I expected it to print out the equivalent ASCII number.

No, even for valid digits, e.g. if you input 1, a will be set with value 1, but not its ASCII number, i.e. 49.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...