当用户输入错误输入时,一次清除 cin 中的整行而不是一个字符
Clear entire line from cin instead of one character at a time when the user enters bad input
我对 cin 的一些命令有疑问。我对 c++ 还很陌生,所以请耐心等待。
我正在做一个简单的计算程序,其中用户输入一个值,程序使用输入进行计算。我正在尝试创建一个循环来检查输入以确保用户输入和编号。经过一些研究,我发现使用 cin.clear
和 cin.ignore
将清除以前的输入,以便用户可以在循环检查后输入一个新值以查看它是否不是数字。它运行良好,除非用户输入的单词大于 1 个字母。然后,它一次循环并删除每个字母,直到清除前一个 cin。有没有办法删除整个单词而不是一次删除一个字符?我觉得我错误地解释了 cin 命令的实际作用。
这是有问题的代码:
//Ask the user to input the base
cout << "Please enter the Base of the triangle" << endl;
cin >> base;
//A loop to ensure the user is entering a numarical value
while(!cin){
//Clear the previous cin input to prevent a looping error
cin.clear();
cin.ignore();
//Display command if input isn't a number
cout << "Not a number. Please enter the Base of the triangle" << endl;
cin >> base;
}
我认为
你可以在网上以多种方式得到答案。这仍然对我有用:
#include <iostream>
#include <limits>
using namespace std;
int main() {
double a;
while (!(cin >> a)) {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
cout << "Wrong input, retry!" << endl;
}
cout << a;
}
此示例比注释中链接的示例更简单,因为您期望用户输入,每行一个输入。
相关文章:
- 无法在 C++ 中输入字符数组
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 在不使用字符串库的情况下输入字符*
- 为什么当我输入字符时,这个特定的 cin.get() 语句在C++中不起作用?
- C++中输入字符数组的特定验证
- 如果用户在 int 中输入字符,如何使用输入
- 当我们在以下程序(C )中输入字符时,该如何解决
- 如何在结构中输入字符到向量
- 用户输入逻辑运算符符号或数字,如果输入字符或字符串则无效
- 输入字符时忽略回车键
- 在 switch 语句中输入字符以进行C++时用户输入错误
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- 如何在应该显示的printf之前输入字符
- C++ 输入字符而不是 int 会导致无限循环.如何检查错误的输入
- 为什么"keep_window_open()"不等待输入字符?
- 为什么我的程序在输入字符时有一个无限循环
- 当提示输入整数值时输入字符时,为什么程序会中断
- 关闭回显后如何再次回显输入字符
- 忽略输入字符
- 从文件的单行读取输入字符