r/cpp_questions • u/Sleepless_night1984 • 5d ago
OPEN Why does entering a string value into a variable declared as an `int` result in an output of 0?
#include "std_lib_facilities.h"
int
main()
{
cout << "Enter your name and age(and press Enter):\n";
string first_name = "???";
int
age = -1;
cin >> first_name >> age;
cout << "Hello, " << first_name << " (age " << age << ")\n";
}I recently started learning C++ using the book "Programming: Principles and Practice Using C++." In one of the author's examples, there is code that, when given the input "22 Carlos," is supposed to output "Hello, 22 (age -1)." However, I get 0 instead of -1, and I don't understand why. Could this have something to do with the C++11 standard?
0
Upvotes
21
u/SilentlyWishing 5d ago
Since C++11, when std::cin >> fails to convert the input to the target type, it stores 0 in the variable. In this example, std::cin >> first_name succeeds because a string accepts any characters. age is an int, so trying to read "Carlos" into it fails: age is set to 0 and the stream enters a fail state (failbit).
5
u/nysra 5d ago
The actual parsing is performed through num_get and that is specified to return 0 for failing to parse integers: https://eel.is/c++draft/locale.num.get#facet.num.get.virtuals-3.3.6
The -1 is ancient, you should get a newer version of that book. And/or use https://www.learncpp.com/
2
u/n1ghtyunso 3d ago
https://www.stroustrup.com/PPP3_errata.html
Its a mistake in the book, but its already a known and acknowledged one.
1
u/flyingron 4d ago
That book is wholely sucky. It starts with the std_lib_facilities.h include and goes downhill from there.
1
u/conundorum 3d ago
Basically, what's happening is that you're not actually reading any data here, because you're extracting a number when there's no number to extract. The operation fails, which causes it to return the fail result instead... and importantly, set a failure flag and leave the data there (so that it's still available if you try again with the correct destination type).
1
u/PittLeElder 5d ago
It has to do with trying to convert the string "Carlos" to an integer.
0
u/mredding 4d ago
Your book is wrong, the author never read Standard C++ IOStreams and Locales.
Streams store the resulting state of the previous IO operation. You can get it from the stream by calling
std::basic_ios::rdstate. You can also get the individual states through accessors likefailandbad.You can also get this state through
explicit operator bool, this means you can just test the stream:A false means the
badbitor thefailbitis set. Thefailbitrepresents a recoverable error, like a parsing error, thebadbitrepresents an unrecoverable error, like get the fire extinguisher bad.You're supposed to check your stream, often like this:
So what happens if there's a parsing error like you describe?
Well, an
std::stringwill parse any character sequence up to a whitespace character. WHAT is a whitespace character? Well that's defined by an instance of thestd::ctypeclass, which is in thestd::localeassigned to the stream. The default locale is the "C" locale if you want to look up its definition. You can always change it or override it or customize it. Sostd::stringparses 22 no problem.That leaves the
int. Streams use thestd::num_getclass to handle the parsing of digit characters and transforming it into an integer type.And the damn thing doesn't parse text.
So what happens? Well, it errors, leaving the first character it erred on in the stream buffer. This trips the stream state to
failbit. Withfailbitorbadbit, ALL IO operations no-op, so not just stream insertion and extraction, but also things like moving the stream position won't work.What does this do to the
int? In THIS SPECIFIC CASE, because it was the parsing of theintthat incurred the failure, the standard says the value of the integer is set to either integer min, integer max, or zero. Now min and max are used to indicate an overflow or underflow error - the integer type is too small to store the value, and the value indicates which way the input went on the number line. Zero is used to indicate a parsing error or any other kind of error.So if you extracted ONLY the
int, and checked the stream and ONLY thefailbitwas set AND the value you got was0, you know you had a parsing error.What happened to you is you errored while extracting the
int, and the stream correctly assigned0and set thefailbit.The standard says for all the basic and standard library value type (
int,std::string, etc.) the original value is preserved if the stream operation no-ops. As for implementation defined type - types you make and stream operators you write for your types, the behavior is unspecified, it's up to you what happens because the compiler cannot force you to write good code.If you want to trigger your scenario to see what happens, you need to trigger an error state at the right time. You can input a name and EOF, and that will get you the name as output and the -1, or you can just enter EOF, and that will get you the questions and -1.
-1
u/Independent_Art_6676 5d ago edited 5d ago
stick to standard styles too.
int age {-1}; //modern style and syntax
breaking up a type name value variable declaration into multiple lines is not going to be well received by other C++ coders. It might be tolerated on the functions (int main, ...) but its kind of strange.
checking input and verifying that it is valid is some of the most important yet difficult tasks. Its deceptively hard to do for some types, esp once you get into unicode and mixed cultures (for example the decimal point and commas in a number are different in USA vs parts of europe).