【发布时间】:2016-12-15 17:37:27
【问题描述】:
在给出 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);
【问题讨论】:
-
quit和Quit又是什么? -
您的代码中还有一些更荒谬的东西::
cin >> ReadInput;读取int值,但您想将其与"q"或"Q"进行比较。 -
这与您要求用户输入的内容完全不同。
-
字符串退出 = "q";字符串退出 = "Q";
-
你还在黑暗和迷雾中徘徊。