简体   繁体   中英

Problem with string input validation (C++)

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM