Getting Integer from String?

J

jobo

Hello,

If I'm given a string that always starts with the word "free" followed
by an integer ("free xx"). How do I parse through the characters and
get to the integer value? Thanks.
 
C

Chris McDonald

jobo said:
If I'm given a string that always starts with the word "free" followed
by an integer ("free xx"). How do I parse through the characters and
get to the integer value? Thanks.

Sounds like homework, but
If char *str = "free 123";
then the address of the '1' will be str+5, or &str[5] .
 
M

mark_bluemel

jobo said:
Hello,

If I'm given a string that always starts with the word "free" followed
by an integer ("free xx"). How do I parse through the characters and
get to the integer value? Thanks.

Is there always a space between "free" and the integer?

Do you know for certain that there will be no characters after the
integer?

If so, then if the string is provided as a char * called (e.g.) "str"
then the integer (as a string) will be at str+5 and you could use one
of the standard functions (from the manual) to convert it to an integer
or long datatype.

There are other approaches, for example there is a function (also in
the manual) for scanning strings and extracting data from them. Or you
could write a routine that searches through the string till it find the
first digit, and then continues, multiplying a running total by 10 (I
presume the integer is in decimal representation) and adding the value
of the next digit, till you run out of digits.
 
A

Andrew Poelstra

Hello,

If I'm given a string that always starts with the word "free" followed
by an integer ("free xx"). How do I parse through the characters and
get to the integer value? Thanks.

scanf("free %d", &n);

Any good C textbook should tell you that.
 
P

Peter Karlsson

Hello,

If I'm given a string that always starts with the word "free" followed
by an integer ("free xx"). How do I parse through the characters and
get to the integer value? Thanks.

strtol?

//Peter
 
X

Xavier Serrand

long int convert (char * s, char *endptr, int base)
{
return strtol (s+3, &endptr, base);
}
 

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,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top