The default value for a variable in C ++ using cin >>

I wrote this C ++ code in the CodeBlocks IDE, but when I run it, it does not give me -1, if it does not read the 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; } 
+7
c ++ c ++ 11
source share
2 answers

The behavior of std :: basic_istream :: operator "> has changed since C ++ 11. Since C ++ 11,

If the extraction fails, zero is written to the value and set to failbit. If the extraction results in a value that is too large or too small for value, std :: numeric_limits :: max () or std :: numeric_limits :: min () is written and the failure flag is set.

Please note that prior to C ++ 11,

If the extraction fails (for example, if a letter was entered where the digit is expected), the value remains unchanged and bitbit is set.

You can check the result of std :: basic_ios :: fail or std :: basic_ios :: operator! and set the default value yourself. For example,

 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: Reset Stream Status

+11
source share

When reading from std::cin there is no support for custom defaults. You should read the user input as a string and check if it is empty. See this question for more details.

Quote from a related question:

 int age = -1; std::string input; std::getline( std::cin, input ); if ( !input.empty() ) { std::istringstream stream( input ); stream >> age; } 
0
source share

All Articles