How do I check if input is an integer/string?

前端 未结 6 1272
一个人的身影
一个人的身影 2021-01-01 07:33

My problem here is I don\'t know how to insert a rule wherein if a user inputted a number on the string, it will cout a warning saying it\'s not valid, same wit

相关标签:
6条回答
  • 2021-01-01 08:12

    cin sets a failbit when it gets input of an invalid type.

    int x;
    cin >> x;
    
    if (!cin) {
        // input was not an integer
    }
    

    You can also use cin.fail() to check if the input was valid:

    if (cin.fail()) {
        // input was not valid
    }
    
    0 讨论(0)
  • 2021-01-01 08:19
        cout << "\n Enter number : ";
        cin >> ch;
        while (!cin) {
            cout << "\n ERROR, enter a number" ;
            cin.clear();
            cin.ignore(256,'\n');
            cin >> ch;
        }
    
    0 讨论(0)
  • 2021-01-01 08:19

    Use the .fail() method of the stream. Something like below:-

       cin >> aString;
    
      std::stringstream ss;
      ss << aString;
      int n;
      ss >> n;
    
      if (!ss.fail()) {
       // int;
      } else {
      // not int;
       }
    
    0 讨论(0)
  • 2021-01-01 08:27

    you could use cin.fail() method! When cin fails it will be true and you could us a while loop to loop until the cin is true:

    cin>>d;
    while(cin.fail()) {
        cout << "Error: Enter an integer number!"<<endl;
        cin.clear();
        cin.ignore(256,'\n');
        cin >> d;
    }
    
    0 讨论(0)
  • 2021-01-01 08:28
    //this program really work in DEV c++
    #include <iostream> 
    using namespace std; 
    int main()
    {
        char input;
        cout<<"enter number or value to check"<<endl;
        cin>>input;
    for(char i='a';i<='z';i++)
    {
        if(input==i)
        {
            cout<<"character"<<endl;
            exit(0);
        }
    }
    for(int i=0;i<=1000;i++)
    {
        if(input==i)
        {
            cout<<"number"<<endl;   
        }
    }
    }
    
    0 讨论(0)
  • 2021-01-01 08:31

    How about something like this:

    std::string str;
    std::cin >> str;
    
    if (std::find_if(str.begin(), str.end(), std::isdigit) != str.end())
    {
        std::cout << "No digits allowed in name\n";
    }
    

    The above code loops through the whole string, calling std::isdigit for each character. If the std::isdigit function returns true for any character, meaning it's a digit, then std::find_if returns an iterator to that place in the string where it was found. If no digits were found then the end iterator is returned. This way we can see if there was any digits in the string or not.

    The C++11 standard also introduced new algorithm functions that can be used, but which basically does the above. The one that could be used instead is std::any_of:

    if (std::any_of(str.begin(), str.end(), std::isdigit))
    {
        std::cout << "No digits allowed in name\n";
    }
    
    0 讨论(0)
提交回复
热议问题