循环应接收输入,直到给出q或Q.虽然循环需要一个整数,但char q或Q会破坏循环并且无法识别。如何让循环识别q或Q来打破循环?
int ReadInput; // Remembers input elements given
string ReadInputString = to_string(ReadInput); // String version of the ReadInput
do
{
bool NoErrors = true; // Make sure there were no errors while reading input
std::cout << "Enter the next element (Enter 'q' to stop): "; // Prompt user for input
cin >> ReadInput;
if (ReadInputString == quit || ReadInputString == Quit) // Enter Q or q to quit
{
break;
}
/* Validation */
if (cin.fail())
{
/* Pass by the bad input */
NoErrors = false; // Note there was a problem
cin.clear(); // Clear the bad input
cin.ignore(); // Ignore the bad input
std::cout << "Invalid number" << endl; // Error message
}
/* Add the input to the list (if there were no problems) */
if (NoErrors)
{
NumbersList.push_back(ReadInput); // Put the given number onto the end of the list
}
} while (ReadInput >= 0);
答案 0 :(得分:-1)
最后在哪里存储数字并不重要。你在整数变量中输入并期望将char存储在那里。所以只需要在那里取一个字符,检查它是否包含数字,如果是,则将其转换为num并继续,如果是char检查它是q或Q并且如果是则中断
int ReadInput;
char temp;
string ReadInputString = to_string(ReadInput); // String version of the ReadInput
do
{
bool NoErrors = true; // Make sure there were no errors while reading input
std::cout << "Enter the next element (Enter 'q' to stop): "; // Prompt user for input
cin >> temp; //store input as char
if (isdigit(temp)) //check input is number or not
ReadInput = temp; //convert input to num if true
else if (temp == 'q' | temp == 'Q') //if not number check for q or Q
break; //break if q
if (ReadInputString == quit || ReadInputString == Quit) // Enter Q or q to quit
{
break;
}
/* Validation */
if (cin.fail())
{
/* Pass by the bad input */
NoErrors = false; // Note there was a problem
cin.clear(); // Clear the bad input
cin.ignore(); // Ignore the bad input
std::cout << "Invalid number" << endl; // Error message
}
/* Add the input to the list (if there were no problems) */
if (NoErrors)
{
NumbersList.push_back(ReadInput); // Put the given number onto the end of the list
}
} while (ReadInput >= 0);