Clear entire line from cin instead of one character at a time when the user enters bad input

青春壹個敷衍的年華 提交于 2020-07-22 21:36:20

问题


I have a question on some commands for cin. I'm still very new to c++ so bear with me.

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.

Here is the code in question:

//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;
}

回答1:


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.



来源:https://stackoverflow.com/questions/28031338/clear-entire-line-from-cin-instead-of-one-character-at-a-time-when-the-user-ente

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!