2

I ran into a problem while trying to validate my user input. Here's my code:

#include <iostream>
#include <string>

using namespace std;

int main() 
{
  string choice;


  cout << "Please type something: ";
  cin >> choice;
  cin.ignore();

  while (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "5")
  {
    cout << "Incorrect choice! Please input a valid number: >_";
    cin >> choice;
    cin.ignore();
  } 

  return 0;
}

When I input "wronginput", that input fell in the while loop and displayed

Incorrect choice! Please input a valid number: >_

Which is good. However, when I try "wrong input", I get a "weird" version of it:

Incorrect choice! Please input a valid number: >_ Incorrect choice! Please input a valid number: >_

My guess is that the space in between is the culprit. Is there any way for me to fix this? Thank you.

2
  • cin reads one word at a time, separated by whitespace. When you pass multiple words, they get queued up and processed in order. Commented Feb 21, 2019 at 22:45
  • use getline instead Commented Feb 21, 2019 at 22:45

2 Answers 2

1

When you enter "wrong input" for input, the line

cin >> choice;

reads and stores "wrong" in choice.

The line

cin.ignore();

ignores only one character. Hence, you stull have "input" and the subsequent newline character in the stream. Next time you read into choice, you get "input" in choice.

That explains the behavior of your program.

In order to fix it, make sure to ignore the rest of the line instead of just one character. Use

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Add

#include <limits>

to be able to use std::numeric_limits.

Sign up to request clarification or add additional context in comments.

Comments

0

That's because std::cin >> choice is a formatted input that will read everything to the next whitespace.

When you type in "wronginput", it reads it all, but if you type in "wrong input", only the "wrong" part will be read. Your while loop will fire, perform std::cin >> choice inside its body once again and that will read "input".

This behaviour causes your program to output the message twice in a row.

How to fix it? Instead of reading a single token, up to the next whitespace, consider reading an entire line.


How to achieve that? Simply instead of using

std::cin >> choice;

use a std::getline function:

std::getline(std::cin, choice);

both outside and inside your while loop.

1 Comment

Thank you, it works. Also, I'll get rid of 'cin.ignore()' since they cause unnecessary pauses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.