Why does this do while loop repeat infinitely? - c++

I want to prompt the user to input an integer, but if the user enters a non-integer, the program should keep demanding an integer until the user complies.
int getInteger(){
int input;
do{
std::cout << "Enter an integer: ";
std::cin >> input;
} while(!(std::cin));
return input;
}
If the user enters an integer, the function returns it.
But if the user enters something like "Hello," the function goes on an infinite, cout-ing "Enter an integer: ".
How do I fix this?

!(std::cin)
will evaluate to true if std::cin is in a bad state, e.g. after an input operation failed. Then, all subsequent input operations will fail immediately and not change cin's error state, thus the infinite loop.
To get the behavior you want, you may use something like
while (!(std::cin >> input)) {
std::cout << "Try again\n";
// Clear away the error state
std::cin.clear();
// Ignore what ever garbage is still in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
In the real world, you may want to handle the (generally not recoverable) failures eof (someone sent an End of File character) and bad (cin is broken, should not happen) different than fail which happens after invalid input. This is, for example, shown on this reference page for ignore. However, this should not bite you in toy programs like yours seems to be.

Streams convert to true while there is none of the failure bits is set. Once a stream entered the failure state, i.e., std::ios_base::failbit (or std::ios_base::badbit) is set for the stream, it stays in that state until the failure bit is cleared using clear(). In addition to clearing the stated you'd also need to get rid of the offending character(s) causing it to get into this state, e.g., using ignore().

Related

Pause Function it is Looping Forever

I am trying to implement a pause function in C++, but it is looping forever.
I am using macOS but I am trying to create a pause function that will work in any system... I believe my cin >> is not capturing '\n' or '\r' from the keyboard and it is looping forever.
void Transferencia::pause() {
char enter = 0;
while(enter != '\n' && enter != '\r') {
cout << "(Press Enter to Continue...) ";
cin >> enter;
}
cin.clear();
}
I want to pause my program until user press the key "enter".
But even when I press "enter/return" it keeps looping...
At very first: enter != '\n' || enter != '\r' is a tautology: Even if enter does equal one of the characters it cannot be equal to the other one. So one of the tests must be true... You actually want to stay in the loop when enter is unequal to both values.
std::cin >> ... won't read data before you press enter, but it will discard the newlines (actually, all whitespace). So it would suffice just to read one single character right without loop (the loop again would get an endless one); solely: If the user doesn't enter anything at all before pressing 'enter' key, there's no character to read from std::cin and we'd still be waiting.
What you can do is reading entire lines:
std::string s;
std::getline(std::cin, s);
That will accept empty lines as well, so does exactly what you want (note: no loop around!).
Edit (stolen from the comments; thanks, Thomas Matthews): An even more elegant way is
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
as it won't create any additional resources that would be discarded afterwards anyway (the std::string object!).
Edit 2:
Depending on type of last input operation, there might still be a newline (or even further data) buffered, e. g. after int n; std::cin >> n;. In this case, you need to skip the input yet buffered. So you would need ignore twice.
However, if the last input operation consumed the newline already (e. g. std::getline – or if there wasn't any preceding input operation at all), then this would lead to user having to press enter twice. So you need to detect what's has been going on before.
std::cin.rdbuf().in_avail() allows you to detect how many characters are yet buffered. So you can have:
if(std::cin.rdbuf().in_avail())
{
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "press enter" << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
On some systems (including mine), though, in_avail can return 0 even though a newline is yet buffered! std::cin.sync_with_stdio(false); can fix the issue; you should execute it before very first input operation. Hopefully, you don't use C++ (streams) and C (scanf, printf, etc) IO intermixed then...
The easiest way to do this is with getline().
cin >> ignores whitespace, newline characters included. getline() will read an entire line, newline character included. However, it does not copy the newline character to the output string. If the user simply hit the enter key and nothing else, you'd end up with an empty string.
So, to get your desired behavior, you would construct your loop like this:
string line;
while(true)
{
cout << "(Press Enter to Continue...) " << endl;
getline(cin, line);
if(line == "")
break;
}
#Aconcagua has answered your question but this is what I want to add in.
Normally, for handling some specific kind of event in computer, we usually follow event-driven paradigm or event-callback.
The idea is there is an event loop that waits for a new event coming into the system. This case, keyboard is an event, the event loop then calls event-callback. What event-callback does is it compares the value of input with some conditions then do some other tasks (it might change some state of the program or notify users).
The idea is keep CPU busy by either 2 ways.
event-driven : do other tasks while waiting for a new event
multithreading: multiple threads in the system. This approach has the disadvantage is at data-race
Have fun

How while(!(cin >> x)) works to re-prompt for input

while(!(cin >> ar[i]))
{
cin.clear(); // clears bad input
while(cin.get() != '\n')
continue;
cout << "Invalid input, please enter valid scores";
}
The above code is from a much larger file. I copied this bit of a code from one of my textbooks and I don't really feel comfortable using it as I do not understand how this works.
I am using it as a measure to handle input errors.
So ar is an empty array of integers, if I decide to enter 'k', then
!(cin >> ar[i])
is true.
From here I clear the input buffer (I think that is correct, I'd like someone to confirm or dispute this please). The terminal then prints "Invalid input..."
Now if I just press Enter nothing happens, but isn't Enter the newline char? So shouldn't the code read
while(cin.get() == '\n'
?
while(!(cin >> ar[i]))
This tries to parse a value from cin and store it in ar[i]. By default, >> skips whitespace first, then sees if the characters in cin describe a legal value for whatever the type of ar[i] is. If a legal value is found, then cin stream state remains good, and its operator bool() const will kick in given the boolean not/! operation, such that the while loop will break.
If parsing fails though, the stream state will be set to one or more of:
bad (if there's some unrecoverable stream error, like stdin supplied over a network connection that gets disconnected),
fail (if the characters just didn't form a legal value for the type), or
eof (end of file, for a "proper" shutdown/close of the input, as supplied by ^D in UNIX/Linux, ^Z in Windows, and the end of input when a program's invoked as in echo input | program).
All the above modalities are described under "State Functions" here.
If the loop is entered due to any of the error conditions above...
{
cin.clear(); // clears bad input
...this does NOT clear any input data from the stream, but does clear the bad, eof and fail state flags, after which further input attempts can be made, though a stream that was in bad or eof state is likely to immediately reenter that state when further input is attempted (but not always - some OS may allow successful input after an eof conditions for std::cin if the user types/generates an EOF code then types actual text again...
while(cin.get() != '\n')
continue;
This tries to read characters from the terminal until a newline \n is encountered. The idea's clearly to clear out the rest of the presumed unparse-able input that might have led to a fail condition earlier. Sadly, if the problem was, or becomes, a bad or eof condition then this loop will hang the program, spinning burning CPU to no avail.
cout << "Invalid input, please enter valid scores";
}
If the problem was simply a mistyped value and no bad or eof condition, then the cout will prompt for further input.
Now if I just press enter nothing happens, but isnt enter the newline char?
Whenever the outer loop is executing cin >> ar[i] it will skip whitespace, including any extra newlines you type, until it sees some input (which may need to be a full newline-terminated line to get flushed by the terminal or program feeding it to the program), or a bad or eof condition. The inner while-loop is not there to get rid of empty lines - it's trying to discard the line with presumed non-numeric text in it.
Corrected code:
while (!(std::cin >> ar[i]))
{
if (std::cin.bad() || std::cin.eof())
{
std::cerr << "Fatal error on cin while reading numbers\n";
exit(EXIT_FAILURE);
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input, please enter valid scores\n: ";
}
The goal of this entire code is to keep printing errors and requesting input until the user enters a valid number before continue further into the program.
The loop that the entire code is enclosed in...
while(!(cin >> ar[i]))
says to loop if the input in the cin stream is invalid. Since ar is an array of integers, the input would be invalid if it is not a number.
cin.clear(); // clears bad input
When the cin stream encounters invalid input, the program begins executing the loop and continues to this line of code. Since the stream encountered invalid input, it has a flag that says there is an error. This requires that you, as the comment puts it, "clear bad input." Basically what this does is get rid of this flag. If this is not done, the flag will remain in the stream and the program will encounter another error next time the cin stream is used, regardless of whether or not the user input is valid.
while(cin.get() != '\n')
continue;
When the program took the input from the user, it took the string, char, whatever was the invalid input, but left the '\n' in the cin stream. To prevent errors the next time the cin stream is used, the program must get rid of that '\n', along with anything else that was lefty behind. cin.get() reads only one char from the cin input stream and returns it. Since the return value of this function is not being assigned to anything, all this does is discard the char that was read. In the case that more than the '\n' was left behind in the stream, this loop checks the value of the read char before disposing of it. This way, the loop keeps executing while the char that is read is NOT '\n'. Or in other words, it loops until the char that is read IS '\n'. The only thing that continue does, is tell the program to skip the rest of the current iteration of the loop and start the next iteration. In this situation, this is equivalent to giving the loop an empty body. You could very well replace continue; with {} and the program would do the exact same thing.
cout << "Invalid input, please enter valid scores";
The program has cleared the flag in cin and has also cleared any data from cin that may have been left behind. Now that all the errors from the invalid input have been handled, there is only one more thing to do. It's time to notify he user that the input was invalid and request new input. If the user enters more invalid input, the loop repeats. If the user enters valid input, the program continues on to the next line of code.

Just wondering what this line does/means to the computer

int value(0);
while (!(std::cin >> value)) { //THIS LINE RIGHT HERE IS BUGGING ME(am really a noob)
cout << "you entered a non-digit character\n";
cin.clear();
cin.ignore();
}
this just stops people from entering letters instead of a number but i wanna know HOW it does it
Treating cin as a Boolean value tells you whether it's in a failure state. if ( cin ) is shorthand for if ( cin.ok() ). So the loop continues as long as the input stream is not OK, after taking some input.
Getting bad input is one way to get to a failure state. To get out of the state, call clear(), and to ignore the offending input, call ignore(). Then you can try again, as in this loop.
If what cin received's data type isn't compatible with value, then basically it returns as false.
cin >> value returns the cin object as a result. And it evaluates as false if the user-entered type doesn't match the specific overload (in your code, it's int), or cannot be implicitly converted to it.
cin is an object of class istream that represents the standard input stream. It corresponds to the cstdio stream stdin.
operator >> overload for streams returns a reference to the same stream and this can be evaluated in a boolean condition to true or false based on internal state of stream through a conversion operator. cin provides formatted stream extraction.
The operation
int value;
!(std::cin >> value)
will fail if numeric value is
entered and will return true if non-numeric value is entered.
cin.clear(); // will reset the state of stream
cin.ignore(); // ignore one or more characters

Abusing cin in while loops for int assignment

simply trying to compare two user defined vectors to see if they are equal, current code:
vector<int> ivec1, ivec2; //vectors, uninitialized
int temp1;
cout << "Enter integers to be stored in ivec1." << endl;
while(cin >> temp1) //takes input from user and creates new element in the vector to store it
{
ivec1.push_back(temp1);
}
int temp2;
cout << "Enter integers to be stored in ivec2." << endl;
while(cin >> temp2) //same as above with different vector
{
ivec2.push_back(temp2);
}
if(ivec1 == ivec2)
cout << "ivec1 and ivec2 are equal!" << endl;
else
cout << "ivec1 and ivec2 are NOT equal!" << endl;
So far it lets me assign values to ivec1 just fine, but as I exit the while loop by entering a letter to make cin fail, it skips the second while block. Out of curiosity I tried putting in other cin statements after the first while loop, and it ignores them all as well.
Does forcing cin to fail cause the program to ignore all other calls for it or something, or is there another problem? If so, how can I get this program to do what I want?
screenshot for your viewing pleasure:
http://img695.imageshack.us/img695/2677/cinfailure.png
*PS. having temp1 and temp2 was just me trying to figure out if using the same int for both assignment loops was causing the problem, anyway I just figured I'd leave it there
You would have to do cin.clear() to reset the stream state. Then you will have to make sure that the offending character is read from the stream (using one of the techniques described here), so that the next input operation does not fail as well.
You mean that you a doing a ctrl-D to give end-of-file for the first loop.
The problem with that is that once EOF is achived it will persist and the second loop will also see the EOF and never read anything.
Instead use a terminating charater such as a blank line or a '.' and specifically test for that in toy while loop instead of while (cin >> tmp1)
Use cin.clear() between the loops. This command resets the state of the stream back to a usable one.
Might be helpful to know that you don't always have to enter an invalid character to exit a loop, you can also use (on windows) a ctrl-z (ctrl-d on other systems) on the console, which stimulates an EOF. You'd still have to cin.clear() (because an EOF still invalidates the stream) - but it's not as dangerous
When the first while loop exits because of failure of std::cin, it also sets the failure flag internally. All you need to clear that flag by writing the following after the first while loop:
scin.clear();
It clears all the failure flag, so that cin can be used to read further inputs.
I found this when I was working through the same problem. I had to add cin.clear() and cin.ignore() to reset the stream between loops and have it recognize the 'cin' calls again.

A loop and a character in int variable doesn't work as i expect

i saw an unusual problem in this code:
#include <iostream>
using namespace std;
int main()
{
int number;
bool repeat=true;
while (repeat)
{
cout<<"\nEnter a number:";
cin>>number;
cout<<"\nNumber is:"
<<number;
cout<<"\nRepeat?:";
cin>>repeat;
}
system("pause");
return 0;
}
here in this code when i put a character such "A" in int type variable while loop repeats over and over and don't ask me whether to repeat or not.
this problem just appear when i put characters not integers.
this appears with for too.
why should happen this?
thanks
After reading in user input which cannot be converted, the input stream is in an invalid state. You need to empty the stream and call the clear method to reset the error bits on the stream in order to resume normal operation.
If you detect that input was not successful (using the input streams state bits, accessible via methods like good() or fail() etc.) you can reset the stream using code similar to this:
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You put cin in an error state when you failed to extract an int from it, and didn't recover. So when you then tried to extract repeat from it, the stream is still in a failed state. You need to check for the failure of number (just use if(cin >> number)).