check if string contains numeric, and check string length of numeric value

I

ief

hi all,

i'm trying to check the length of a numeric value in a string.
this is what i need to do:
I have a string "Mystring (253)"
and a string "SecondString (31548745754)"

Now i have to check if the string contains more than 3 numeric
characters because i must only process the ones with more than 3.

Thx in advance,

ief
 
M

msalters

(e-mail address removed) schreef:
hi all,

i'm trying to check the length of a numeric value in a string.
this is what i need to do:
I have a string "Mystring (253)"
and a string "SecondString (31548745754)"

Now i have to check if the string contains more than 3 numeric
characters because i must only process the ones with more than 3.

for( char c = '0'; c <= '9'; ++c )
sum += std::count(..., c );

HTH,
Michiel Salters
 
S

Simon Elliott

i'm trying to check the length of a numeric value in a string.
this is what i need to do:
I have a string "Mystring (253)"
and a string "SecondString (31548745754)"

Now i have to check if the string contains more than 3 numeric
characters because i must only process the ones with more than 3.


You could use std::strpbrk() to find the start of the string, and
std::strtoul() to convert the number. Use the pointer returned by
std::strtoul() to determine the length of the numeric string.

Or you could use std::sscanf().
 
J

James Daughtry

and std::strtoul() to convert the number
What if the number is out of range for an unsigned long? The example
shows that you can't just assume the minimum portable length and claim
ignorance, or you'll probably get incorrect output for some of the
strings. It's easier to just leave the type as string and just count
characters:

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

struct digit {
bool operator()(int c) const { return std::isdigit(c); }
};

int main()
{
std::string a("Mystring (253)");
std::string b("SecondString (31548745754)");
digit d;

std::string::iterator ai
= std::find_if(a.begin(), a.end(), d);
std::string::iterator bi
= std::find_if(b.begin(), b.end(), d);

std::cout << "Length of number in a: "
<< std::count_if(ai, a.end(), d) << '\n';
std::cout << "Length of number in b: "
<< std::count_if(bi, b.end(), d) << '\n';
}
 
X

X-Centric

this works fine, but how can i determine the length of my char , or any
string of int type
 
X

X-Centric

Thanks James, srry for previous post, you message wasn't shown...
That did the trick.

ief
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top