How to make cin take only numbers

后端 未结 4 1042
青春惊慌失措
青春惊慌失措 2020-11-22 07:30

Here is the code

double enter_number()
{
  double number;
  while(1)
  {

        cin>>number;
        if(cin.fail())
        {
            cin.clear()         


        
相关标签:
4条回答
  • 2020-11-22 07:53

    I would use std::getline and std::string to read the whole line and then only break out of the loop when you can convert the entire line to a double.

    #include <string>
    #include <sstream>
    
    int main()
    {
        std::string line;
        double d;
        while (std::getline(std::cin, line))
        {
            std::stringstream ss(line);
            if (ss >> d)
            {
                if (ss.eof())
                {   // Success
                    break;
                }
            }
            std::cout << "Error!" << std::endl;
        }
        std::cout << "Finally: " << d << std::endl;
    }
    
    0 讨论(0)
  • 2020-11-22 07:55

    When cin encounters an input it can't properly read in to the variable specified (such as inputing a character into an integer variable), it goes into an error state and leaves the input in it's buffer.

    You have to do several things to properly handle this scenario.

    1. You have to test for this error state.
    2. You have to clear the error state.
    3. You have to either alternatively handle the input data that generated the error state, or flush it out and reprompt the user.

    The following code provides one of numerous methods of doing these three things.

    #include<iostream>
    #include<limits>
    using namespace std;
    int main()
    {
    
        cout << "Enter an int: ";
        int x = 0;
        while(!(cin >> x)){
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Invalid input.  Try again: ";
        }
        cout << "You enterd: " << x << endl;        
    }
    

    You could just pass in some large value to cin.ignore like 1000 and it's likely to behave exactly the same for all practical purposes.

    You can also test cin after the input attempt and handle it that way, something like if(!cin){//clean up the error} .

    Check out the istream reference for other member functions to handle stream state: http://cplusplus.com/reference/iostream/istream/

    0 讨论(0)
  • 2020-11-22 07:57
    #include<iostream>
    #include<cstdlib>
    #include<cstring>
    using namespace std;
    int get_int(void);
    int main()
    {
        puts("Enter a number");
        cout<<"The integer is "<<get_int()<<endl;
        return 0;
    }
    int get_int(void)
    {
        char str[20];
        char* end;
        int num;
        do{
            fgets(str,20,stdin);
            str[strlen(str)-1]='\0';
            num=strtol(str,&end,10);
            if(!(*end))
                return num;
            else
            {
                puts("Please enter a valid integer");
                num=0;
            }
        }while(num==0);
    }
    

    This works fine for any integer. It can even check if you enter a space or any other character after the integer. The only problem is that it does not make use of std::cin. But, the problem with std::cin is that it ignores any space character after the integer and happily takes the integer as input.

    0 讨论(0)
  • 2020-11-22 07:59

    I would prefer the following code. Among many codes to clear this question out of our minds, I think this is most appropriate code I found online.

    #include <iostream>
    #include <limits>
    using namespace std;
    
    int main(){
        int n;
        while(!(cin >> n)) {
            cin.clear(); // to clear the buffer memory
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Please enter a valid integer!";
        }
        cout << "Your Integer: " << n << endl;
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题