Ok, I am a newcomer to C++ and running into an issue. I am using the introductory book by Stroustrup and attempting some basic code with int that I am running into a problem with. According to the book, the code below should cause the output to give a result of "-1" for the age if no integer is entered (for example, if I enter '22 Carlos'). While the string outputs fine, the int gives me a value of 0 if no int is entered. I have entered everything exactly as they stated in the book, so can someone please tell me where I'm going wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
usingnamespace std;
inlinevoid keep_window_open() {char ch; cin>>ch;}
// The above code uses the standard library directly, eliminating the need for the std_lib_facilities.h
int main ()
{
cout << "Please enter your first name and age (followed by 'enter'):\n";
string first_name = "???" ; // first name is a variable of type string, default is "???"
int age = -1; // age is a variable of type int, default is "-1"
cin >> first_name; // places input from user into the string variable
cin >> age; // places input from user into the int variable
cout << "Hello, " << first_name << ", age " << age << "!\n";
}
> According to the book, the code below should cause the output to give a result of
> "-1" for the age if no integer is entered ... I have entered everything exactly as they
> stated in the book, so can someone please tell me where I'm going wrong?
You have not gone wrong anywhere.
A new version of the International Standard for C++ (C++11) was published after the book was written.
Before C++11, the behaviour was as stated in the book; on input failure, the value of age would not be changed; age would continue to hold the previous value of -1
Since C++11, on input failure, the value of age would be set to zero.
You are using an implementation that conforms to the current standard.
What?! I didn't know that! That's stupid!
If there is no value to assign to an object, why assign anything at all?
I'll definitely have to read up on the rationale for that...
Well thank you for that information. I'll have to look around for other changes made by that new version. I am at a bit of a loss though as to why they made a change like that, but then again I am new to all this, so sure there must be some good reasoning behind it.
If extraction fails, failbit is set and the value stored in the numeric variable is:
a. Zero if no part of the input could be converted (eg. if "hello" was entered where a number was expcted).
b. The largest representable positive value if the input represents a value that would have been larger.
c. The largest representable negative value (or zero for unsigned integer types) if the input represents a value that would have been smaller.