C++ problems involving getline() and a loop - c++

I am working an a school assignment and am beating my head against a wall right now trying to figure out why my program is not behaving as I'd like it to!
int main(){
string input;
char choice;
bool getChoice(char);
string getInput();
CharConverter newInput;
do{
cout << "Please enter a sentence.\n";
getline(cin, input);
cout << newInput.properWords(input) << endl;
cout << newInput.uppercase(input) << endl;
cout << "Would you like to do that again?\n";
cin >> choice;
} while (getChoice(choice) == true);
return 0;
}
This program works fine on the first round, but I am having a problem when getChoice() == true, and the do while block is looped a second time. On the second loop, the program asks for me to enter a sentence again, but then just jumps to "Would you like to do that again?" without allowing user input or outputting the results of the properWords() and uppercase() functions. I suspect that there is something about getline that I do not understand, but I have yet to find it through my googling. Any help out there?
edit: there was a mistake in my original explanation.

This is because reading input with getline does not mix well with reading input character-by-character. When you enter the Y/N character to indicate if you want to proceed or not, you also press Enter. This puts \n in the input buffer, but >> does not take it from there. When you call getline, the \n is right there, so the function returns an empty string right away.
To fix this, make choice a std::string, use getline to read it, and send the first character to getChoice function, like this:
string choice;
...
do {
...
do {
getline(cin, choice);
} while (choice.size() == 0);
} while (getChoice(choice[0]));

Related

Avoid bad user input (string when what's asked is an integer)

I have an infinite while loop, where the user is asked for a number.
My problem is very simple: If the input is a string, I want to re-ask user for input, outputting the message "Enter a valid choice: ".
I searched, and looks like I should check for cin.fail(), then call cin.clear() and cin.ignore().
Here's my code:
int main() {
int choice;
bool failed = false;
while (true) {
if (failed) cout << "Enter a valid choice: ";
else cout << "Enter a number: ";
cin >> choice;
if (cin.fail()) {
cin.clear();
cin.ignore();
failed = true;
}
}
return 0;
}
However, this doesn't really fix my problem. Of course, it isn't printing infinitely, but for each letter extra letter , it prints another "Enter a valid choice:"
Seems like I need to call cin.ignore() for each extra letter.
Any other way of doing this?
You have an infinite loop because you are not breaking the loop even when valid input is enter. Is that what you really want? If so, at the least, you are not resetting the failed flag in valid input.
More importantly, when invalid input is entered, you are not ignoring everything that was enteted, you are only ignoring 1 char at a time. That is why you see extra prompts.
Try this instead :
int main() {
int choice;
while (true) {
cout << "Enter a number: ";
while (!(cin >> choice)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter a valid choice: ";
}
}
return 0;
}
The reason it is printing so many times is because you are only clearing the state of cin, but aren't clearing the input buffer. You can do so in multiple ways:-
Use fflush(stdin) to clear the input buffer.This is the C method and can be done by including cstdio header.
Use the cin.ignore to ignore all characters in the current input stream. You can do this by replacing the line cin.ignore() which ignores a single character by this code cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') which ignores the entire line. For this you need the limits header.
Finally you can do the same with a simple loop like while (cin.get() != '\n'){continue;} which ignores all characters till new line.
Also another approach to the same problem is to take the input in form of a string and use the strtol() or the isdigit() functions to check if the input is valid.
By the way the infinite loop is because you have not used the break statement to terminate the loop. So you can avoid this by adding
if(!failed)
break;
Also you need to change the state of Failed at the entry of each loop by adding
failed=false;
at the start of the loop body.

If you enter the desired input twice, it outputs twice?

Heres my example:
while (response == 'y')
{
playOneGame();
cout << "Great! Do you want to play again (y/n)? ";
cin >> response;
}
And if you type in: yy
It prints the output twice:
"Great! Do you want to play again (y/n)? Great! Do you want to play again (y/n)? "
I would just like to understand why. This program is written in C++ if that matters. Thanks.
Since you are comparing it to a char (result == 'y'), I'm assuming result is also a char.
The cin operation is going just read one char, and leave the second one on the input buffer. Then, the next time through the loop, it reads the second 'y' without any additional user input required.
If you want to be sure there is nothing left in the buffer, read until you get a line terminator. Or you can read into a string:
string response = "y";
// continues on anything that starts with lowercase 'y'.
// exits on anything else.
while (response.length() >= 1 && response[0] == 'y') // length check maybe unnecessary?
{
playOneGame();
cout << "Great! Do you want to play again (y/n)? ";
cin >> response;
}
It is not clear the type of response, but I assume it is char.
char response;
while(response=='y'){
playOneGame();
cout << "Great! Do you want to play again (y/n)? ";
cin >> response;
}
cin reads all the chars until you stop sending chars to it. Simply, cin gets whole terminal line so when you press 'yy', while loop runs twice.
If loop runs twice and prints the message two times:
1. It doesn't start game again.
2. Even, it starts the game, when it is over, for the second y, it does starts game again without asking.
Modify your code to read one char and continue. You can use getche() to get one char and continue.
This is exactly what you need. Apply the code below to your real case.
#include<iostream>
#include<limits>
using namespace std;
int main()
{
char response = 0;
while(cin >> response){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You enterd: " << response << endl;
}
return 0;
}
Here is the explanation:
Why would we call cin.clear() and cin.ignore() after reading input?

How to skip 'enter' in cin.ignore()

I write a code to check char 'exit' in int cin. But I find that I need to set delimiters in cin.ignore such as '\n' and input it when running command and I think that is not friendly.
How can I change the code to skip the extracting step , maybe using other code instead of cin.ignore?
Sorry for everyone who try to read my English and answer as I not a native English user.
I mean cin.ignore is to extracts and discards characters until the given character is found, is it have a way to clear the cin buffer in C++ with discarding characters without extracting?
void checkcin(int &y)
{
string input = "", ans;
cin.clear();
cin.ignore(INT_MAX, '\n');
getline(cin, input);
while (input == "exit")
{
cout << "Are you sure to exit: ";
cin >> ans;
if (ans == "yes")
{
cout << "Bye." << endl;
exit(0);
}
else if (ans == "no")
{
cout << "Then welcome back!";
cout << "Input again: ";
cin >> input;
}
}
y = std::stoi(input);
}
The first parameter in the "std::cin.ignore()" that you are using just comes down to a very large number. This should be the maximum number of characters that the input buffer can hold. This number may be different on different systems or even header files for different compilers.
You need to press enter twice because there is nothing in the buffer to ignore. It is waiting for something to be entered to ignore. some people will use this to pause the program before the "return 0;".

cin.get(); doesn't work when I put it in a if statement

I used cin.get() to get the program to pause and wait for user input, and it works fine. The moment I put it in an if statement, it just skips that "wait" period and continues on with the code? How can I solve this. Here is the section that is not working.
do
{
cout << "\n\n\nEnter the number of one of the following and I will explain!\n";
cout << "1.integer 2.boolian 3.floats 4.doubles 5.character";
cout << "\n\n[when you are done type 'done' to continue]\n\n";
cin >> option;
if (option = 1);
{
cout << "\nInteger is the variable abbreviated as 'int' this allows C++ to only";
cout << "\nreadwhole and real numbers \n\n";
cin.get(); //this is the part where it just skips.. it should wait
}
} while (var = 1);
The problem is that cin >> option will extract whatever integer is in the input stream but will leave the following newline character (which is there from hitting enter after typing in the value). When you do cin.get() it is simply extracting that newline character which is already there. Like so many other questions like this, the solution is to empty the input stream after you've extracted into option:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You are also using assignment (=) where you should be comparing for equality (==).

cin condition checking error

I am a beginner programmer learning c++. I am having a nagging issue with the cin command.
In the program section below, if I enter a wrong type at the 1st cin command, the program will not execute any of the following cin commands at all, but will execute the rest of the program.
//start
#include <iostream>
using namespace std;
int main()
{
int x=0;
cout << endl << "Enter an integer" << endl;
//enter integer here. If wrong type is entered, goes to else
if (cin >> x){
cout << "The value is " << x << endl;
}
else {
cout << "You made a mistake" << endl; //executes
cin.ignore();
cin.clear();
}
cout << "Check 1" << endl; //executes
cin >> x; //skips
cout << "Check 2" << endl; //executes
cin >> x; //skips
return 0;
}
//end
Instead of the if else, if i put the same concept in a loop
while (!(cin >> x))
the program goes into an infinite loop upon enterring a wrong input.
Please help me explain this phenomenon, as the text book i am following says the code typed above should work as intended.
Thank you
cin is an input stream. If an error occurs cin goes into a let's call it "error occured" state. While in this state no character input can be made, your request to collect a character from the input stream will be ignored. With clear() you clear the error and the input stream stops ignoring you.
Here is the ignore function prototype
istream& ignore ( streamsize n = 1, int delim = EOF );
This function gets characters from the input stream and discards them, but you can't get any character if your stream is ignoring you, so you have to first clear() the stream then ignore() it.
Also, a note on the side: If someone inputs, for example "abc", on the first input request your cin gets only one character that is 'a' and "bc" stays in the buffer waiting to be picked up, but the next call to cin gets the 'b' and 'c' stays in the buffer, so you again end up with an error.
The problem with this example is that the cin.ignore() if no arguments are handed to it only ignores 1 character after you clear(). and the second cin gets 'c' so you still have a problem.
A general solution to this problem would be to call
cin.ignore(10000, '\n');
The first number just has to be some huge number that you don't expect someone would enter, I usually put in 10000.
This call makes sure that you pick up all the characters from the false input or that you pick up every character before the enter was pressed so your input stream doesn't get into the "error occurred" state twice.
You may also want to try
if ( std::cin.fail() )
as a backup to prevent a crash due to input of the wrong type when prompted