Home > Enterprise >  How to check whether a string input from the user contains a number or not?
How to check whether a string input from the user contains a number or not?

Time:12-19

The title says it all. I'm looking to check if a string contains even a single digit somewhere. No idea how to do this. If there is a pre-built function for this, I'd still like an unorthodox, long way of actually doing it (if you know what I mean).

Thanks!

CodePudding user response:

If there is a pre-built function for this, I'd still like an unorthodox, long way of actually doing it (if you know what I mean).

You could just use a simple for-loop and check if any of the characters present in the string are digits and return true if any is found, otherwise false:

#include <string>
#include <cctype>
// ...

bool contains_number(std::string const& s) {
    for (std::string::size_type i = 0; i < s.size(); i  )
        if (std::isdigit(s[i]))
            return true;
    return false;
}

Or if you're fine with using std::string::find_first_of().

bool contains_number(std::string const& s) {
    return s.find_first_of("0123456789") != std::string::npos;
}

CodePudding user response:

using std::isdigit in iostream It will return true or false

#include <iostream>

using namespace std;

bool isnumber(string n){
    for (int i = 0;i < n.size();i  ){
        if (isdigit(n[i]) == 1){
            return true;
        }
    }
    return false;
}
int main(){
   string n;
   cin >> n;
   if (isnumber(n)){
       cout << "Have number in string";
   }else{
       cout << "Doesn't have number in string";
   }
   return 0 ;
}
  •  Tags:  
  • c
  • Related