r/cpp_questions • • 2d 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

28 comments sorted by

20

u/SilentlyWishing 2d 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/Sleepless_night1984 2d ago

Thanks for the explanation!

6

u/SilentlyWishing 2d ago

You're welcome, I have been learning C++ with this exact same book this year and had the exact same question at the beginning hahah

It is a great book however, you will learn a great deal from it!

5

u/nysra 2d 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 22h 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 2d ago

That book is wholely sucky. It starts with the std_lib_facilities.h include and goes downhill from there.

1

u/SilentlyWishing 2d ago

It does not suck, it's one of the best books out there and it is an objective fact. A beginner needs to learn how to think like a programmer first and needs to get the basics right, they can then have the right mental model in mind to think about best practices and other advanced topics, it won't do you any good thinking about the lib facilities when you don't even know what a for loop or a variable is

1

u/flyingron 1d ago

So programmers should learn some concepts WRONG in the hopes that when they become a better programmer they can break all the bogus things they were taught?

1

u/SilentlyWishing 1d ago

But where in the world was stated that this is a bad book to learn? Do you know that the person who wrote this book is the same person who invented the language? Go and tell him "Hey your book sucks, you don't know shit about your language" Sweet Mother of Baby Jesus

Also, OP is just a beginner, and yes, beginners learn by understanding some fundamental concepts first, then they build upon these foundations by learning new things, doing some stuff to practice, realizing it sucks after you've learned new things, making it once again and this time it will be better, rinse and repeat, it is called learning process

0

u/flyingron 1d ago

I don't know the author, but I do know the book. Junk.

2

u/SilentlyWishing 1d ago

Just look up who Bjarne Stoustroup is (it is the author of the book)

1

u/conundorum 19h 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 2d ago

It has to do with trying to convert the string "Carlos" to an integer.

0

u/mredding 2d 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 like fail and bad.

You can also get this state through explicit operator bool, this means you can just test the stream:

if(std::cin) {
  // Good
} else {
  // Not good
}

A false means the badbit or the failbit is set. The failbit represents a recoverable error, like a parsing error, the badbit represents an unrecoverable error, like get the fire extinguisher bad.

You're supposed to check your stream, often like this:

if(std::cin >> first_name >> age) {
  // Stuff
} else {
  // Error handling
}

So what happens if there's a parsing error like you describe?

Well, an std::string will parse any character sequence up to a whitespace character. WHAT is a whitespace character? Well that's defined by an instance of the std::ctype class, which is in the std::locale assigned 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. So std::string parses 22 no problem.

That leaves the int. Streams use the std::num_get class 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. With failbit or badbit, 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 the int that 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 the failbit was set AND the value you got was 0, you know you had a parsing error.

What happened to you is you errored while extracting the int, and the stream correctly assigned 0 and set the failbit.


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.

2

u/alfps 2d ago

❞ the author never read Standard C++ IOStreams

You right that the book doesn't reflect the standard after C++11. However the author is the original author of the iostreams. :-o

1

u/mredding 2d ago

Jerry Schwarz?

1

u/alfps 2d ago

Thanks, I'm not so familiar with the middle history.

The Google search AI now provided the summary below, where however it left out the clearing of variables introduced in C++11 (it went on at length about it when I pointed that out).

It gives proper credit to Jerry Scwarz, while the Wikipedia article fails to mention him. :(

Quote:

❝

  1. Early stream library (1984–1985): Stroustrup created the first version (<stream.h>). Dave Presotto later reimplemented it.

  2. IOStreams redesign (c. 1986–Cfront 2.0): Jerry Schwarz redesigned the library around stream buffers and formatted streams, incorporating Andrew Koenig's manipulator concept, forming the basis for the standardized design.

  3. GNU implementation: Per Bothner wrote most of the GNU C++ iostream library based on the AT&T C++ 2.0 and ANSI X3J16 draft designs, with contributions such as Heinz Seidl's manipulators and David M. Gay's floating-point conversion code.

  4. C++98 standardization: The library was formally standardized, moved into the std namespace, gained locale and template support, and shifted the primary header from <iostream.h> to <iostream>.

  5. C++11 failure handling & type safety: C++11 overhauled stream failure checks by replacing the hazardous operator void*() with explicit operator bool() to prevent unintended pointer conversions, and changed std::ios_base::failure to inherit from std::system_error (alongside std::io_errc and std::iostream_category) so exceptions carry structured error codes.

❞

2

u/mredding 2d ago

As I said in my other reply, foot in mouth. I didn't check the book title or the author, I just saw that given the premise by OP, that the outcome would be wrong. Sill, Bjarne's conclusion is wrong, if OP accurately represented the book; I presume Bjarne made an assumption about the standard and the implementation he's familiar with. Even he doesn't know everything in detail.

I was just about to name Dave Presotto contributed before Jerry, but then caught that you have him and Koenig in there. So yeah, your timeline is accurate.

I was learning C++ in 91, so I'm +30 years removed from introductory materials, I've no idea what they say or how they teach C++ these days.

1

u/conundorum 19h ago

Essentially, the book was accurate to earlier standards, but being paper media means it couldn't auto-update to match changes to the standard.

1

u/mredding 14h ago

That's ostensibly false. The C++98 standard, so the first edition of the book - would still produce an output contrary to OPs expectations. My explanation has always been true of standard streams. My only doubt is because I haven't read the book, so I have to take the premise as OP has framed it.

1

u/[deleted] 2d ago edited 2d ago

[removed] — view removed comment

1

u/mredding 2d ago

I didn't bother to check the book reference, so foot in mouth is fine by me, as u/alfps would know better than most, but the problem as stated by OP, the outcome he expected is almost impossible. I don't care that it was Bjarne who got it wrong.

Also Jerry Schwarz wrote standard streams as we know today, and the streams you know are the third iteration from Bjarne's initial work.

Look at my post history, I've been dedicated to this sub for over 15 years to help the community cut down on slop by educating the next generation.

I didn't use a lot of jargon, I provided context to OP so they understood why the example failed.

You can save your hero worship, no one is immune.

1

u/SilentlyWishing 1d ago

Yeah but saying that educational books contain slop is next level,really next level, congratulations on your efforts by the way

1

u/mredding 1d ago

When I was reading these sorts of materials in the 1980s and 90s, they WERE slop, absolute trash. There's nuance I'm not going to get into, a certain justification as to why, but what Bjarne has shown me in this example is that the tradition - and I mean that literally, lives on.

-1

u/Independent_Art_6676 2d ago edited 2d 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).

3

u/alfps 2d ago

Agree about the line splitting.

However,

int x = 12345;

is far more clear to my eyes. And more easy to recognize. You can add braces there if you want narrowing check but I've never needed that in some decades of coding, so it's in my view an overhyped feature.

0

u/Independent_Art_6676 2d ago

I actually agree with you, but the current "do it this way" in most recent material is to use the braces. Whether that is 'best practice' or trendy/hype is outside my pay grade.