How do I terminate input without crowding cin with a value? [duplicate] - c++

Google Code University's C++ tutorial used to have this code:
// Description: Illustrate the use of cin to get input
// and how to recover from errors.
#include <iostream>
using namespace std;
int main()
{
int input_var = 0;
// Enter the do while loop and stay there until either
// a non-numeric is entered, or -1 is entered. Note that
// cin will accept any integer, 4, 40, 400, etc.
do {
cout << "Enter a number (-1 = quit): ";
// The following line accepts input from the keyboard into
// variable input_var.
// cin returns false if an input operation fails, that is, if
// something other than an int (the type of input_var) is entered.
if (!(cin >> input_var)) {
cout << "Please enter numbers only." << endl;
cin.clear();
cin.ignore(10000,'\n');
}
if (input_var != -1) {
cout << "You entered " << input_var << endl;
}
}
while (input_var != -1);
cout << "All done." << endl;
return 0;
}
What is the significance of cin.clear() and cin.ignore()? Why are the 10000 and \n parameters necessary?

The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

You enter the
if (!(cin >> input_var))
statement if an error occurs when taking the input from cin. If an error occurs then an error flag is set and future attempts to get input will fail. That's why you need
cin.clear();
to get rid of the error flag. Also, the input which failed will be sitting in what I assume is some sort of buffer. When you try to get input again, it will read the same input in the buffer and it will fail again. That's why you need
cin.ignore(10000,'\n');
It takes out 10000 characters from the buffer but stops if it encounters a newline (\n). The 10000 is just a generic large value.

Why do we use:
1) cin.ignore
2) cin.clear
?
Simply:
1) To ignore (extract and discard) values that we don't want on the stream
2) To clear the internal state of stream. After using cin.clear internal state is set again back to goodbit, which means that there are no 'errors'.
Long version:
If something is put on 'stream' (cin) then it must be taken from there. By 'taken' we mean 'used', 'removed', 'extracted' from stream. Stream has a flow. The data is flowing on cin like water on stream. You simply cannot stop the flow of water ;)
Look at the example:
string name; //line 1
cout << "Give me your name and surname:"<<endl;//line 2
cin >> name;//line 3
int age;//line 4
cout << "Give me your age:" <<endl;//line 5
cin >> age;//line 6
What happens if the user answers: "Arkadiusz Wlodarczyk" for first question?
Run the program to see for yourself.
You will see on console "Arkadiusz" but program won't ask you for 'age'. It will just finish immediately right after printing "Arkadiusz".
And "Wlodarczyk" is not shown. It seems like if it was gone (?)*
What happened? ;-)
Because there is a space between "Arkadiusz" and "Wlodarczyk".
"space" character between the name and surname is a sign for computer that there are two variables waiting to be extracted on 'input' stream.
The computer thinks that you are tying to send to input more than one variable. That "space" sign is a sign for him to interpret it that way.
So computer assigns "Arkadiusz" to 'name' (2) and because you put more than one string on stream (input) computer will try to assign value "Wlodarczyk" to variable 'age' (!). The user won't have a chance to put anything on the 'cin' in line 6 because that instruction was already executed(!). Why? Because there was still something left on stream. And as I said earlier stream is in a flow so everything must be removed from it as soon as possible. And the possibility came when computer saw instruction cin >> age;
Computer doesn't know that you created a variable that stores age of somebody (line 4). 'age' is merely a label. For computer 'age' could be as well called: 'afsfasgfsagasggas' and it would be the same. For him it's just a variable that he will try to assign "Wlodarczyk" to because you ordered/instructed computer to do so in line (6).
It's wrong to do so, but hey it's you who did it! It's your fault! Well, maybe user, but still...
All right all right. But how to fix it?!
Let's try to play with that example a bit before we fix it properly to learn a few more interesting things :-)
I prefer to make an approach where we understand things. Fixing something without knowledge how we did it doesn't give satisfaction, don't you think? :)
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate(); //new line is here :-)
After invoking above code you will notice that the state of your stream (cin) is equal to 4 (line 7). Which means its internal state is no longer equal to goodbit. Something is messed up. It's pretty obvious, isn't it? You tried to assign string type value ("Wlodarczyk") to int type variable 'age'. Types doesn't match. It's time to inform that something is wrong. And computer does it by changing internal state of stream. It's like: "You f**** up man, fix me please. I inform you 'kindly' ;-)"
You simply cannot use 'cin' (stream) anymore. It's stuck. Like if you had put big wood logs on water stream. You must fix it before you can use it. Data (water) cannot be obtained from that stream(cin) anymore because log of wood (internal state) doesn't allow you to do so.
Oh so if there is an obstacle (wood logs) we can just remove it using tools that is made to do so?
Yes!
internal state of cin set to 4 is like an alarm that is howling and making noise.
cin.clear clears the state back to normal (goodbit). It's like if you had come and silenced the alarm. You just put it off. You know something happened so you say: "It's OK to stop making noise, I know something is wrong already, shut up (clear)".
All right let's do so! Let's use cin.clear().
Invoke below code using "Arkadiusz Wlodarczyk" as first input:
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;
cin.clear(); //new line is here :-)
cout << cin.rdstate()<< endl; //new line is here :-)
We can surely see after executing above code that the state is equal to goodbit.
Great so the problem is solved?
Invoke below code using "Arkadiusz Wlodarczyk" as first input:
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;;
cin.clear();
cout << cin.rdstate() << endl;
cin >> age;//new line is here :-)
Even tho the state is set to goodbit after line 9 the user is not asked for "age". The program stops.
WHY?!
Oh man... You've just put off alarm, what about the wood log inside a water?* Go back to text where we talked about "Wlodarczyk" how it supposedly was gone.
You need to remove "Wlodarczyk" that piece of wood from stream. Turning off alarms doesn't solve the problem at all. You've just silenced it and you think the problem is gone? ;)
So it's time for another tool:
cin.ignore can be compared to a special truck with ropes that comes and removes the wood logs that got the stream stuck. It clears the problem the user of your program created.
So could we use it even before making the alarm goes off?
Yes:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
The "Wlodarczyk" is gonna be removed before making the noise in line 7.
What is 10000 and '\n'?
It says remove 10000 characters (just in case) until '\n' is met (ENTER). BTW It can be done better using numeric_limits but it's not the topic of this answer.
So the main cause of problem is gone before noise was made...
Why do we need 'clear' then?
What if someone had asked for 'give me your age' question in line 6 for example: "twenty years old" instead of writing 20?
Types doesn't match again. Computer tries to assign string to int. And alarm starts. You don't have a chance to even react on situation like that. cin.ignore won't help you in case like that.
So we must use clear in case like that:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
But should you clear the state 'just in case'?
Of course not.
If something goes wrong (cin >> age;) instruction is gonna inform you about it by returning false.
So we can use conditional statement to check if the user put wrong type on the stream
int age;
if (cin >> age) //it's gonna return false if types doesn't match
cout << "You put integer";
else
cout << "You bad boy! it was supposed to be int";
All right so we can fix our initial problem like for example that:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
if (cin >> age)
cout << "Your age is equal to:" << endl;
else
{
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
cout << "Give me your age name as string I dare you";
cin >> age;
}
Of course this can be improved by for example doing what you did in question using loop while.
BONUS:
You might be wondering. What about if I wanted to get name and surname in the same line from the user? Is it even possible using cin if cin interprets each value separated by "space" as different variable?
Sure, you can do it two ways:
1)
string name, surname;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin >> surname;
cout << "Hello, " << name << " " << surname << endl;
2) or by using getline function.
getline(cin, nameOfStringVariable);
and that's how to do it:
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
The second option might backfire you in case you use it after you use 'cin' before the getline.
Let's check it out:
a)
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endl;
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
If you put "20" as age you won't be asked for nameAndSurname.
But if you do it that way:
b)
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endll
everything is fine.
WHAT?!
Every time you put something on input (stream) you leave at the end white character which is ENTER ('\n') You have to somehow enter values to console. So it must happen if the data comes from user.
b) cin characteristics is that it ignores whitespace, so when you are reading in information from cin, the newline character '\n' doesn't matter. It gets ignored.
a) getline function gets the entire line up to the newline character ('\n'), and when the newline char is the first thing the getline function gets '\n', and that's all to get. You extract newline character that was left on stream by user who put "20" on stream in line 3.
So in order to fix it is to always invoke cin.ignore(); each time you use cin to get any value if you are ever going to use getline() inside your program.
So the proper code would be:
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cin.ignore(); // it ignores just enter without arguments being sent. it's same as cin.ignore(1, '\n')
cout << "Your age is" << age << endl;
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
I hope streams are more clear to you know.
Hah silence me please! :-)

use cin.ignore(1000,'\n') to clear all of chars of the previous cin.get() in the buffer and it will choose to stop when it meet '\n' or 1000 chars first.

Related

getline removes first character; removal of cin.ignore(); does not resolve

int main()
{
for (int i = 0; i < 4; ++i)
{
cout << "Please enter Employee #" << (i+1) << "'s" << " name: ";
cin.ignore();
getline(cin, employee[i].employeeName);
cout << "Please enter Employee #" << (i+1) << "'s hours worked: ";
cin >> employee[i].hoursWorked;
cout << "Please enter Employee #" << (i+1) << "'s hourly rate: ";
cin >> employee[i].hourlyRate;
cout << "Please enter Employee #" << (i+1) << "'s Federal Tax Rate: ";
cin >> employee[i].fedtaxRate;
cout << "Please enter Employee #" << (i+1) << "'s State Tax Rate: ";
cin >> employee[i].statetaxRate;
cout << endl;
}
As the title says, I currently have cin.ignore(); to help with taking in a full name like "Barkley, Charles" (it does a fine job, except it truncates the first character leaving us with "arkley, Charles" when printed) but when I remove cin.ignore();, like 99% of the StackOverflow questions that have been answered say, nothing happens. In fact, it even gets worse: on the second loop, it will take the second line of the second loop and put it on the first line of the second loop. It's just a mess. Oh, and cin.getline doesn't work either. I tried that in conjunction with cin.sync and no dice. Regular plain old vanilla cin >> causes the same second line on first line problem. I don't know what to do. I haven't found a SO article that covers this (seemingly) edge case. Thanks for the help.
As with many input questions, the problem exists because you're mixing line-based and item-based input.
What will happen is that the final cin >> employee[i].statetaxRate; will leave the stream pointer pointing to a position immediately after the last valid character of its type.
That's likely to be the newline at the end of the line so, when you then go back to get the next name (without the cin.ignore), it will read that as an empty line.
You may think you can fix it by placing the cin.ignore at the end of the loop but you can run into other problems with that. Specifically, since that form simply skips one character, entering:
123<space><newline>
will simply skip the <space> and you'll have exactly the same issue.
A quick fix is to simply read the entire rest of the line with something like (at the end of the loop):
{
std::string junk;
getline(cin, junk);
}
and this will prep the input stream so you're at the start of the next line.
The other possibility (and this is preferred since the first time you enter abc where it's expecting a number is going to cause you grief) is to read all your items as lines and then use string processing to put them into numeric variables, something like strtod().

Why is exit(0); giving me a std:string... error?

I'm new to C++. I decided to not watch the next tutorial and put my skills to use, by making a funny Mind Reader application. I'm pleased with myself, however, even though I've ironed out most bugs, I still have one concerning the exit function. I read the C++ documentation for it, and I'm not sure what I did wrong. I did exit(0);. I have a very weird error, which is:
no match for call to '(std::string {aka std::basic_string<char>}) (int)
I have searched online, however I am still unaware of what the problem is. My error is on line 59 (marked in the code):
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
//declaring variables to be used later
string name;
string country;
int age;
//header goes below
cout << "#######################################";
" ############ MIND READER ############"
"#######################################\n\n";
//asks if the user would like to continue and in not, terminates
cout << "Would like you to have your mind read? Enter y for yes and n for no." << endl;
cout << "If you do not choose to proceed, this program will terminate." << endl;
string exitOrNot;
//receives user's input
cin >> exitOrNot;
//deals with input if it is 'y'
if (exitOrNot == "y"){
cout << "Okay, first you will need to sync your mind with this program. You will have to answer the following questions to synchronise.\n\n";
//asks questions
cout << "Firstly, please enter your full name, with correct capitalisation:\n\n";
cin >> name;
cout << "Now please enter the country you are in at the moment:\n\n";
cin >> country;
cout << "This will be the final question; please provide your age:\n\n";
cin >> age;
//asks the user to start the sync
cout << "There is enough information to start synchronisation. Enter p to start the sync...\n\n";
string proceed;
cin >> proceed;
//checks to see if to proceed and does so
if (proceed == "p"){
//provides results of mind read
cout << "Sync complete." << endl;
cout << "Your mind has been synced and read.\n\n";
cout << "However, due to too much interference, only limited data was aquired from your mind." << endl;
cout << "Here is what was read from your mind:\n\n";
//puts variables in sentence
cout << "Your name is " << name << " and you are " << age << " years old. You are based in " << country << "." << endl << "\n\n";
cout << "Thanks for using Mind Reader, have a nice day. Enter e to exit." << endl;
//terminates the program the program
string exit;
cin >> exit;
if (exit == "e"){
exit(0); // <------------- LINE 59
}
}
}
//terminates the program if the input is 'n'
if (exitOrNot == "n"){
exit(0);
}
return 0;
}
Thanks
The local variable exit shadows other identifiers from outer scopes with the same name.
To illustrate with a smaller example:
int main()
{
int i;
{
int i;
i = 0; // assign to the "nearest" i
// the other i cannot be reached from this scope
}
}
Since the only exit visible is an object of type std::string, the compiler sees exit(0) as a call to operator()(int) and throws a hissy fit when it doesn't find one among std::string members.
You can either qualify the name (std::exit(0);) or rename the variable. And since all of your code is in main you can simply say return 0; instead.
Try using return 0; or return EXIT_SUCCESS;. It's the exact same thing. Also, you can only input one word into a cin. Instead, use getline(cin, string name); If it still doesn't work, add a cin.ignore(); before your getline(cin, string name);, like this:
//stuff
string country;
cout << "Now please enter the country you are in at the moment:\n\n";
cin.ignore();
getline(cin, country);
//stuff
return 0;
The problem is arrising because you declared a standard keyword as the name of a local variable.
Now as the local variable is of type sting it is not able to take it as its value.

Loop fails during first attempt

I am completing a lab assignment where the user is prompted for the type if fish they wish to order and to enter the price per pound. The user needs to be prompted for the type of fish and the price two times before the report prints.
The problem is that the program ends before the first instance of the loop has completed. (The way the code is written the titles on the report will print twice, but that was in the instructions.)
The code is below and any assistance is greatly appreciated.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
float price;
string fishType;
int counter = 0;
// Change the console's background color.
system ("color F0");
while (counter < 3){
// Collect input from the user.
cout << "Enter the type of seafood: ";
cin >> fishType; // <------ FAILS AT THIS POINT. I GET THE PROMPT AND AT THE "ENTER" IT DISPLAYS THE REPORT
cout << "Enter the price per pound using dollars and cents: ";
cin >> price;
counter++;
}
// Display the report.
cout << " SEAFOOD REPORT\n\n";
cout << "TYPE OF PRICE PER" << endl;
cout << "SEAFOOD POUND" << endl;
cout << "-------------------------------" << endl;
cout << fixed << setprecision(2) << showpoint<< left << setw(25)
<< fishType << "$" << setw(5) << right << price << endl;
cout << "\n\n";
system ("pause");
return 0;
}
The new line character will not have been consumed by the read, using std::istream::operator>>(float), of the price:
cin >> price; // this will not consume the new line character.
The presence of the new line character during the next read, using operator>>(std::istream, std::string)), into fishType:
cin >> fishType; // Reads a blank line, effectively.
and then the user input that was intended to be the next fishType will be read (and fail to be) by the price as it will not be a valid float value.
To correct, ignore() until the next new line character after the read of the price. Something like:
cin.ignore(1024, '\n');
// or: cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Always check the status of input operation to determine if they were successful or not. This is easily achieved:
if (cin >> price)
{
// success.
}
If the fishType can contain spaces then using operator>>(std::istream, std::string) is not appropriate as it will stop reading at the first whitespace. Use std::getline() instead:
if (std::getline(cin, fishType))
{
}
When the user enters input a new line character will be written to stdin, i.e cin:
cod\n
1.9\n
salmon\n
2.7\n
On first iteration of the loop:
cin >> fishType; // fishType == "cod" as operator>> std::string
// will read until first whitespace.
and cin now contains:
\n
1.9\n
salmon\n
2.7\n
then:
cin >> price; // This skips leading whitespace and price = 1.9
and cin now contains:
\n
salmon\n
2.7\n
then:
cin >> fishType; // Reads upto the first whitespace
// i.e reads nothin and cin is unchanged.
cin >> price; // skips the whitespace and fails because
// "salmon" is not a valid float.

getline(cin.name) gets skipped

I call a function from a function in C++ that has the line getline(cin,name) where name is a string. the first time through the loop, the program does not wait for input. It will on all other passes through the loop. Any ideas on why?
void getName (string& name)
{
int nameLen;
do{
cout << "Enter the last Name of the resident." << endl << endl
<< "There should not be any spaces and no more than 15"
<< " characters in the name." << endl;
getline(cin,name);
cout << endl;
nameLen = name.length();// set len to number of characters input
cout << "last" << name << endl;
}
while (nameLen < LastNameLength);
return;
}
Make sure there isn't left overs since the last time you read something from cin, like:
In an earlier point in your program:
int number;
cin >> number;
The input you give:
5
Later in the program:
getline(cin,name);
and getline will seem to not be called, but rather it collected the newline from the last time you took input because when you use cin >> it leaves new lines.
It may be because of the input stream. The getline function stops reading input after is receives the first newline char. If for example there are multiple newlines within the buffer of std::cin - the getline will return every time it encounters one.
Check the input you are expecting.
Do you have any:
cin << variableName;
lines of code? I ran into getline() skipping run-time errors when I was using:
cin << intvariable and subsequently getline(cin, variable).
This is because the cin stream object holds a buffer of input. When you enter the newline character I assume it is trunacated from the stream going to the variable asisgnment, yet is still contained within the cin object instance itself.
One workaround I used is cin.ignore(); after the cin << integer statement.
Another user mentioned parsing all input from getline into integers, floats - not root beer -, and strings. Good luck and check your code for the dual use of cin & getline().

Why would we call cin.clear() and cin.ignore() after reading input?

Google Code University's C++ tutorial used to have this code:
// Description: Illustrate the use of cin to get input
// and how to recover from errors.
#include <iostream>
using namespace std;
int main()
{
int input_var = 0;
// Enter the do while loop and stay there until either
// a non-numeric is entered, or -1 is entered. Note that
// cin will accept any integer, 4, 40, 400, etc.
do {
cout << "Enter a number (-1 = quit): ";
// The following line accepts input from the keyboard into
// variable input_var.
// cin returns false if an input operation fails, that is, if
// something other than an int (the type of input_var) is entered.
if (!(cin >> input_var)) {
cout << "Please enter numbers only." << endl;
cin.clear();
cin.ignore(10000,'\n');
}
if (input_var != -1) {
cout << "You entered " << input_var << endl;
}
}
while (input_var != -1);
cout << "All done." << endl;
return 0;
}
What is the significance of cin.clear() and cin.ignore()? Why are the 10000 and \n parameters necessary?
The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.
You enter the
if (!(cin >> input_var))
statement if an error occurs when taking the input from cin. If an error occurs then an error flag is set and future attempts to get input will fail. That's why you need
cin.clear();
to get rid of the error flag. Also, the input which failed will be sitting in what I assume is some sort of buffer. When you try to get input again, it will read the same input in the buffer and it will fail again. That's why you need
cin.ignore(10000,'\n');
It takes out 10000 characters from the buffer but stops if it encounters a newline (\n). The 10000 is just a generic large value.
Why do we use:
1) cin.ignore
2) cin.clear
?
Simply:
1) To ignore (extract and discard) values that we don't want on the stream
2) To clear the internal state of stream. After using cin.clear internal state is set again back to goodbit, which means that there are no 'errors'.
Long version:
If something is put on 'stream' (cin) then it must be taken from there. By 'taken' we mean 'used', 'removed', 'extracted' from stream. Stream has a flow. The data is flowing on cin like water on stream. You simply cannot stop the flow of water ;)
Look at the example:
string name; //line 1
cout << "Give me your name and surname:"<<endl;//line 2
cin >> name;//line 3
int age;//line 4
cout << "Give me your age:" <<endl;//line 5
cin >> age;//line 6
What happens if the user answers: "Arkadiusz Wlodarczyk" for first question?
Run the program to see for yourself.
You will see on console "Arkadiusz" but program won't ask you for 'age'. It will just finish immediately right after printing "Arkadiusz".
And "Wlodarczyk" is not shown. It seems like if it was gone (?)*
What happened? ;-)
Because there is a space between "Arkadiusz" and "Wlodarczyk".
"space" character between the name and surname is a sign for computer that there are two variables waiting to be extracted on 'input' stream.
The computer thinks that you are tying to send to input more than one variable. That "space" sign is a sign for him to interpret it that way.
So computer assigns "Arkadiusz" to 'name' (2) and because you put more than one string on stream (input) computer will try to assign value "Wlodarczyk" to variable 'age' (!). The user won't have a chance to put anything on the 'cin' in line 6 because that instruction was already executed(!). Why? Because there was still something left on stream. And as I said earlier stream is in a flow so everything must be removed from it as soon as possible. And the possibility came when computer saw instruction cin >> age;
Computer doesn't know that you created a variable that stores age of somebody (line 4). 'age' is merely a label. For computer 'age' could be as well called: 'afsfasgfsagasggas' and it would be the same. For him it's just a variable that he will try to assign "Wlodarczyk" to because you ordered/instructed computer to do so in line (6).
It's wrong to do so, but hey it's you who did it! It's your fault! Well, maybe user, but still...
All right all right. But how to fix it?!
Let's try to play with that example a bit before we fix it properly to learn a few more interesting things :-)
I prefer to make an approach where we understand things. Fixing something without knowledge how we did it doesn't give satisfaction, don't you think? :)
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate(); //new line is here :-)
After invoking above code you will notice that the state of your stream (cin) is equal to 4 (line 7). Which means its internal state is no longer equal to goodbit. Something is messed up. It's pretty obvious, isn't it? You tried to assign string type value ("Wlodarczyk") to int type variable 'age'. Types doesn't match. It's time to inform that something is wrong. And computer does it by changing internal state of stream. It's like: "You f**** up man, fix me please. I inform you 'kindly' ;-)"
You simply cannot use 'cin' (stream) anymore. It's stuck. Like if you had put big wood logs on water stream. You must fix it before you can use it. Data (water) cannot be obtained from that stream(cin) anymore because log of wood (internal state) doesn't allow you to do so.
Oh so if there is an obstacle (wood logs) we can just remove it using tools that is made to do so?
Yes!
internal state of cin set to 4 is like an alarm that is howling and making noise.
cin.clear clears the state back to normal (goodbit). It's like if you had come and silenced the alarm. You just put it off. You know something happened so you say: "It's OK to stop making noise, I know something is wrong already, shut up (clear)".
All right let's do so! Let's use cin.clear().
Invoke below code using "Arkadiusz Wlodarczyk" as first input:
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;
cin.clear(); //new line is here :-)
cout << cin.rdstate()<< endl; //new line is here :-)
We can surely see after executing above code that the state is equal to goodbit.
Great so the problem is solved?
Invoke below code using "Arkadiusz Wlodarczyk" as first input:
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;;
cin.clear();
cout << cin.rdstate() << endl;
cin >> age;//new line is here :-)
Even tho the state is set to goodbit after line 9 the user is not asked for "age". The program stops.
WHY?!
Oh man... You've just put off alarm, what about the wood log inside a water?* Go back to text where we talked about "Wlodarczyk" how it supposedly was gone.
You need to remove "Wlodarczyk" that piece of wood from stream. Turning off alarms doesn't solve the problem at all. You've just silenced it and you think the problem is gone? ;)
So it's time for another tool:
cin.ignore can be compared to a special truck with ropes that comes and removes the wood logs that got the stream stuck. It clears the problem the user of your program created.
So could we use it even before making the alarm goes off?
Yes:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
The "Wlodarczyk" is gonna be removed before making the noise in line 7.
What is 10000 and '\n'?
It says remove 10000 characters (just in case) until '\n' is met (ENTER). BTW It can be done better using numeric_limits but it's not the topic of this answer.
So the main cause of problem is gone before noise was made...
Why do we need 'clear' then?
What if someone had asked for 'give me your age' question in line 6 for example: "twenty years old" instead of writing 20?
Types doesn't match again. Computer tries to assign string to int. And alarm starts. You don't have a chance to even react on situation like that. cin.ignore won't help you in case like that.
So we must use clear in case like that:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
But should you clear the state 'just in case'?
Of course not.
If something goes wrong (cin >> age;) instruction is gonna inform you about it by returning false.
So we can use conditional statement to check if the user put wrong type on the stream
int age;
if (cin >> age) //it's gonna return false if types doesn't match
cout << "You put integer";
else
cout << "You bad boy! it was supposed to be int";
All right so we can fix our initial problem like for example that:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
if (cin >> age)
cout << "Your age is equal to:" << endl;
else
{
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
cout << "Give me your age name as string I dare you";
cin >> age;
}
Of course this can be improved by for example doing what you did in question using loop while.
BONUS:
You might be wondering. What about if I wanted to get name and surname in the same line from the user? Is it even possible using cin if cin interprets each value separated by "space" as different variable?
Sure, you can do it two ways:
1)
string name, surname;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin >> surname;
cout << "Hello, " << name << " " << surname << endl;
2) or by using getline function.
getline(cin, nameOfStringVariable);
and that's how to do it:
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
The second option might backfire you in case you use it after you use 'cin' before the getline.
Let's check it out:
a)
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endl;
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
If you put "20" as age you won't be asked for nameAndSurname.
But if you do it that way:
b)
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endll
everything is fine.
WHAT?!
Every time you put something on input (stream) you leave at the end white character which is ENTER ('\n') You have to somehow enter values to console. So it must happen if the data comes from user.
b) cin characteristics is that it ignores whitespace, so when you are reading in information from cin, the newline character '\n' doesn't matter. It gets ignored.
a) getline function gets the entire line up to the newline character ('\n'), and when the newline char is the first thing the getline function gets '\n', and that's all to get. You extract newline character that was left on stream by user who put "20" on stream in line 3.
So in order to fix it is to always invoke cin.ignore(); each time you use cin to get any value if you are ever going to use getline() inside your program.
So the proper code would be:
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cin.ignore(); // it ignores just enter without arguments being sent. it's same as cin.ignore(1, '\n')
cout << "Your age is" << age << endl;
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
I hope streams are more clear to you know.
Hah silence me please! :-)
use cin.ignore(1000,'\n') to clear all of chars of the previous cin.get() in the buffer and it will choose to stop when it meet '\n' or 1000 chars first.