1

I'm trying to examine a C++ code from my tutorial book. I've written this using CodeBlocks IDE:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
/*...*/
using namespace std;
/*...*/
int main (void){

    cout << "Please enter name and age: \n\n:>";
    string _sInput = "";
    int _intInput = -1;
    cin >> _sInput >> _intInput;
    cout << "Hello " << _sInput << "!\n";
    cout << "You have aged " << _intInput << " years.";
}

Based on what was discussed in the book by Mr. Stroustrup, now that I have given the variable _intInputan intial value, if I input wrong data like James Boy I am supposed to receive an output like this:

Hello James!

You have aged -1 years.

But what I get is You have aged 0 years. just like the time I have not given an intial value.
Is there anything wrong with my code or what?!

Vynylyn
  • 172
  • 11
  • Someone will surely confirm or dispute soon, but I seem to remember that reading from cin was changed so, that on parse errors the value is still set, to 0 in case of integer. This prevents undefined behaviour caused by uninitialised variables. Proper way to test if reading failed is to test stream status with the status methods of the class. – hyde Mar 13 '19 at 11:45
  • 1
    Note that if you leave local variable uninitialised it will be *default initialised*, which for int means uninitialised, so you wouldn't necessarily get 0, you could get anything when using the value (technically it is undefined behaviour, so theoretically the program could do *anything*). – hyde Mar 13 '19 at 11:47
  • 2
    @hyde You mean: [istream behavior change in C++ upon failure](https://stackoverflow.com/q/19522504/583833) ? – Borgleader Mar 13 '19 at 11:49
  • 1
    @hyde I have initialised it. – Vynylyn Mar 13 '19 at 11:49
  • @Vynylyn I was referring to "just like the time I have not given an intial value" text in your question. – hyde Mar 13 '19 at 11:52
  • @Borgleader Yep. Thanks for digging that out, put the link to the answer I just wrote. – hyde Mar 13 '19 at 11:58

2 Answers2

3

Since C++11, when reading integer or floating point number from istream fails, the target variable is set to 0. See this (cppreference.com) or this (stack overflow.com) for more on that.

This means, you can't use a sentinel value to detect parse error, you have to use for example fail() method to check if there was some error.

hyde
  • 60,639
  • 21
  • 115
  • 176
3

As per C++11, the value is set to zero, when an error occurs. See "If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value..." for more info.

Alexander Falk
  • 499
  • 8
  • 21