简体   繁体   中英

Using getline(cin, var) twice produces error when doing string comparison (==)

void command_menu(){
  string command = "default000",
         command_upper;
  bool incorrect_input = false;
  do{
    clear_replit();
    default_display();
    cout << "\nType 'commands' to see a list of options, or enter a command.\n";
    if(command == "default000"){}
    else{
      cout << special_text("red","'");
      cout << special_text("green", command) << special_text("red", "'");
      cout << special_text("red", " is not a recognized command.\n");
    }
    getline(cin, command);
    command_upper = string_toupper(command);
    if(command_upper == "COMMANDS"){
      list_of_commands();
    }

I'm having a problem getting this snippet of code to work which hasn't been resolved by adding cin.ignore() or cin.clear() or both before or after the getline command.

If I type in "commands" at the prompt, the if(command = "commands") check passes. If I first type in gibberish ("blah"), I get re-prompted as expected, and if I enter "commands" it does store the word "commands" in the getline variable, but now the if(command == "commands") check fails.

If you need a working code, my entire project can be found here: https://repl.it/@AndreLouis/Scrabble#main.cpp

Reproduce the error by first typing "commands" and seeing the program execute, then run the program again, type "blah", and then type "commands".

The problem is with incorrect_input value. When you compare command_upper to "COMMANDS" you need to make sure to set that variable to false , otherwise after the first failed check, the value will always be true

Set incorrect_input fo false at the start of the loop:

bool incorrect_input = false;
do{
    incorrect_input = false;
    clear_replit();
...

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