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.
Asked
Active
Viewed 106 times
0
-
5Define "any number". 1? -1? 123.123? ---12.84e19? three? 零番目? ①? – deviantfan Jun 22 '15 at 20:03
-
1Need 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 Answers
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
- 674
- 6
- 15
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,778
- 8
- 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
- 204,454
- 14
- 159
- 270
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
- 654
- 5
- 17