0

What would be the easiest and simplest beginner friendly way to check for any number in a input string, if it finds number return error.

  • 5
    Define "any number". 1? -1? 123.123? ---12.84e19? three? 零番目? ①? – deviantfan Jun 22 '15 at 20:03
  • 1
    Need more details. Are you checking that a string contains no digits? – Barry Jun 22 '15 at 20:05
  • possible duplicate of [How to determine if a string is a number with C++?](http://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c) – Axalo Jun 22 '15 at 20:38

5 Answers5

2

There is a function called isdigit, which checks whether its input is a decimal digit. Hope this helps.

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

int main() {
        string s = "abc1abc";
        for(int i = 0; i < s.length(); i++) {
                if(isdigit(s[i])) {
                        cout << "Found numer at pos: " << i << endl;
                        return -1;
                }
        }
        return(0);
}
ChrisD
  • 634
  • 5
  • 14
1

The simplest way will be to check the entire string, character by character and see if it is a number of not.

std::string yourString;

for(int i=0;i<yourString.size();i++)
{
    if(yourString[i]<='9' && yourString[i]>='0')
    {
         std::cout << "Err" << std::endl;
         break;
    }
}

Another solution will be to use a regex. A regex that check if a number is present is \d

A B
  • 497
  • 2
  • 9
0

You could use string::find. Just look for a 1, 2, 3, 4, 5, 6, 7, 8, 9 or 0 and if you find one return an error.

Olivier Poulin
  • 1,688
  • 5
  • 15
0

You can use std::find_if and std::isdigit to check whether a string has a number or not.

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

bool hasNumber(std::string const& s)
{
   return (std::find_if(s.begin(), s.end(), [](char c) { return std::isdigit(c); }) != s.end());
}

int main(int argc, char** argv)
{
   for ( int i = 1; i < argc; ++i )
   {
      if ( hasNumber(argv[i]) )
      {
         std::cout << "'" << argv[i] << "' contains a number.\n";
      }
      else
      {
         std::cout << "'" << argv[i] << "' does not contain a number.\n";
      }
   }

   return 0;
}

When run with:

./prog abcd12 12akdk akdk1dkdk akske

The output is:

'abcd12' contains a number.
'12akdk' contains a number.
'akdk1dkdk' contains a number.
'akske' does not contain a number.
R Sahu
  • 196,807
  • 13
  • 136
  • 247
0

Most simple:

boost::algorithm::any(str, std::isdigit)

And if you don't link with boost:

std::any_of(str.begin(), str.end(), std::isdigit)
Curve25519
  • 584
  • 4
  • 17