问题描述
我对cin的某些命令有疑问.我对C ++还是很陌生,所以请多多包涵.
I have a question on some commands for cin. I'm still very new to c++ so bear with me.
我正在做一个简单的计算程序,其中用户输入一个值,然后程序使用输入进行计算.我试图创建一个循环来检查输入,以确保用户输入的数字.经过一些研究,我发现使用 cin.clear
和 cin.ignore
会清除先前的输入,因此用户可以在循环检查后看是否没有输入新值.一个号码.效果很好,除非用户输入的单词大于1个字母.然后,它循环并一次删除每个字母,直到清除上一个cin.有没有办法删除整个单词,而不是一次删除一个字符?我觉得我误解了cin命令的实际作用.
I'm doing a simple calculation program where the user inputs a value and the program does a calculation with the input. I'm attempting to create a loop that checks the input to ensure the user inputted and number. After some research I found that using cin.clear
and cin.ignore
will clear the previous input so the user can input a new value after the loop checks to see if its not a number. It works well, except when the user inputs a word larger then 1 letter. It then loops and removes each letter one at a time until the previous cin is cleared. Is there a way to remove the entire word rather then one character at a time? I feel I have incorrectly interpreted what the cin commands actually do.
这是有问题的代码:
//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;
}
推荐答案
我认为您可以在网上以多种方式获得答案.仍然对我有用:
I think you could get the answer in many ways on the net. Still this works for me:
#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;
}
此示例比注释中链接的示例更简单,因为您希望用户输入,每行一个输入.
This example is simpler than the one linked in the comments since you are expecting input from the user, one input per line.
这篇关于用户输入错误的输入时,从cin而不是一个字符中清除整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!