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!