0

I am new to C++. I saw many discussions about a while loop asking the user whether to run again (y/n) output the prompt (enter a value: ) twice, but don't get what I should do.

I have:

int main()
{
    std::cout << '\n' << "Calculate the amino acid number from a coding nucleotide. \n\n";

    char again = 'Y';

    while (again == 'y' || again == 'Y')
    {
    std::cout << "Enter a *coding* nucleotide number: ";
    int x{};
    std::cin >> x;

    (do something with x)

    std::cout << '\n' <<"Again (y/n)?";
    std::cin >> again;
    }
    return 0;
}

This is fine. Users will know that an integer >= 1 is required as input. But I wanted to add some input validation, so if a integer < 1 or a float or text string is entered, it is discarded and the user is prompted again until proper input is entered.

https://www.youtube.com/watch?v=S3_jCTb3fm0 provided an input validation. I inserted like this:

int main()
{
std::cout << '\n' << "Calculate the amino acid number from a coding nucleotide. \n\n";

char again = 'Y';
while (again == 'y' || again == 'Y')
   {
    string str = "";
    int x{0};
    bool cont = true;
    while (cont){
        std::cout << "Enter a *coding* nucleotide number: ";
        getline(std::cin, str);
        stringstream ss(str);
        if (ss >> x && x >= 1){
            cont = false;
        }
     }

    (do something with x)

    std::cout << '\n' <<"Again (y/n)?";
    std::cin >> again;

    }
        return 0;
}

The prompt "Enter a coding nucleotide number: " appears just once first time through, but after answering "Again (y/n)?" with "y" it reads: "Enter a coding nucleotide number: " "Enter a coding nucleotide number: ". How, exactly do I fix this?

Thank you!

  • 1
    Classic mistake due to `std::cin >> again;` which only reads what it needs from the stream and leaves the newline in there. So the next call to `std::getline` pulls any leftover characters and the newline from the stream. Read your "again" prompt with `std::getline` for the easiest fix. This type of question is asked about 10 times every day on Stack Overflow. – paddy Nov 01 '21 at 03:03

0 Answers0