I have a char variable with the name of the entrance, the user must enter Y / N, if something else is entered, you must display a message about the incorrectness of the entered data and ask to enter again, until Y / N is entered or y / n. For some reason, I have a cycle of an error message that displays as much as the wrong characters I type, and I can’t understand why.

Here is the code itself:

char entrance; cin >> entrance; while((entrance != 78) && (entrance != 110) && (entrance != 89) && (entrance != 121)) { cout << "Неверный ввод! Следует ввести Y/N, попробуйте еще раз:"; cin >> entrance; cout << "" << endl; } 

In general, I am not even sure of the correctness of this approach, this is only a small part of a large OOP assignment. It is necessary to create a program for booking a hotel and this small part of the code is responsible for the continuation of the program, depending on the data entry.

  • "I can not understand why so" And why should it be wrong? Why are you surprised that the error message is issued as many times as you entered the wrong characters? Your processing is done character by character. - AnT pm
  • one
    And you know, you don’t need to replace characters with numerical representations - though it’s so much more understandable - while((entrance != 'y') && (entrance != 'Y') && (entrance != 'n') && (entrance != 'N')) ? - Harry

2 answers 2

Because only the first character is assigned to the input variable, all the others remain in the input stream buffer and inserted without your demand when cin and similar input functions are called next time. To better understand all this, you can check how the program works:

 #include <iostream> using namespace std; int main() { cin.get(); cin.get(); } 

If more than one character is entered, the next cin.get() will not wait for user input, but will take a character from the input stream buffer. When this is not displayed in the console. By the way, Enter is also a character.

    In your case, you can get by with goto, although many people say that this is a bad tone, but if your hands are straight, then there will be no problem with this. This is the usual jmp code in assembler. It is used very simply, a label is created, where we can later jump using goto

    A simple example: if the client enters the value <= 0, then we jump to the section of the ErrorGO code, where we are repeatedly asked to enter

      void foo() { int testvalue = 0; ErrorGO: std::cin >> testvalue if(testvalue <= 0) goto ErrorGO; }