C 循环回收整数直到给出q
C++ Loop recieves integers until given Q
循环应接收输入,直到给出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);
最终存储数字的位置无关紧要。您正在使用Integer变量输入,并希望将炭存储在那里。因此,只需在那里带一个字符,检查它是否包含一个数字,如果是,请将其转换为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);
相关文章:
- C++:如何循环通过向量中的整数元素
- 如何获取矢量循环的整数位置
- 如何仅使用 While 循环在给定范围内找到可被 7 整除的计数整数
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 在控制台上输出我从文件中读取的整数,将程序插入无限循环
- 如何用字符终止整数输入循环?
- 使用 size_t 初始化循环变量时的整数下溢
- while 循环对非整数的响应很奇怪
- 程序终止,而不是继续整数输入验证循环
- 在基于范围的循环范围内的双/整数使用和数据缩小
- 符号和未签名整数表达式之间的比较,以进行循环误差
- 计算用户使用循环输入的整数数量
- 而无符号整数条件的循环
- 为什么它在循环 C++ 中反转整数的数字
- 虽然循环与整数不起作用
- C++ 通过 range for 循环将整数输入到矢量中;随机 0
- 显示六个整数中的最小偶数和奇数,而不使用循环和数组
- 如何在输入整数时中断 for 循环
- 如何打破循环以在C 中获取整数数组
- 有没有一种方法可以简化这个c++整数循环数组?