Reputation: 23
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.
Upvotes: 0
Views: 168
Reputation: 694
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)
Upvotes: 0
Reputation: 206597
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.
Upvotes: 0
Reputation: 674
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);
}
Upvotes: 2
Reputation: 487
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
Upvotes: 1
Reputation: 1796
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.
Upvotes: 0