Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for variable in C++ using cin >>

Tags:

c++

c++11

I have written this code in C++ in the CodeBlocks IDE but when I run it, it doesn't give me -1 if it doesn't read a number, it gives me 0. Is there something wrong with the code?

#include "iostream"

using namespace std;

int main()
{
    cout<<"Please enter your first name and age:\n";
    string first_name="???"; //string variable
                            //("???" means "don't know the name")
    int age=-1; //integer variable (-1 means "don't know the age")
    cin>>first_name>>age; //read a string followed by an integer
    cout<<"Hello, " <<first_name<<" (age "<<age<<")\n";

    return 0;
}
like image 802
calm-tedesco Avatar asked Nov 04 '15 10:11

calm-tedesco


People also ask

What does cin >> n mean in C++?

cin is the standard input stream. Usually the stuff someone types in with a keyboard. We can extract values of this stream, using the >> operator. So cin >> n; reads an integer. However, the result of (cin >> variable) is a reference to cin .

What is default value of data type in C?

datatype − The datatype of variable like int, char, float etc. variable_name − This is the name of variable given by user. value − Any value to initialize the variable. By default, it is zero.

What is the return value of cin?

cin >> num1 returns a reference to cin . If cin >> num1 is able to read an int , cin continues to be in a good state; if the attempt at input fails, cin is set to a state that is not good. In if (cin) , the condition is true if cin is in a good state.

What is the default value of newly declared variable?

Variables of any "Object" type (which includes all the classes you will write) have a default value of null. All member variables of a Newed object should be assigned a value by the objects constructor function.


1 Answers

The behaviour of std::basic_istream::operator>> has changed from C++11. Since C++11,

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, std::numeric_limits::max() or std::numeric_limits::min() is written and failbit flag is set.

Note that until C++11,

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

You could check the result by std::basic_ios::fail or std::basic_ios::operator! and set the default value by yourself. Such as,

string first_name;
if (!(cin>>first_name)) {
    first_name = "???";
    cin.clear(); //Reset stream state after failure
}

int age;
if (!(cin>>age)) {
    age = -1;
    cin.clear(); //Reset stream state after failure
}

cout<<"Hello, " <<first_name<<" (age "<<age<<")\n";

See also: Resetting the State of a Stream

like image 116
songyuanyao Avatar answered Oct 07 '22 05:10

songyuanyao