Another newbie question: extract doubles from strings

P

philbo30

Easy question, just trying to get a head start on learning a few
things...I don't need code, just looking to learn the important stuff
faster....

I have two strings:

Volume: 826100.32
Cost: $ 61243.71

loaded as:

char vol[30];
char cost[30];


I want to extract the "numbers" out of both the volume string and cost
string, as doubles.

What's the "best" approach?

Thanks again, sorry for asking such basic questions.
 
G

Guest

philbo30 said:
Easy question, just trying to get a head start on learning a few
things...I don't need code, just looking to learn the important stuff
faster....

I have two strings:

Volume: 826100.32
Cost: $ 61243.71

Are the labels part of the strings, or are they only a description? Is
the spacing identical for all strings? Is the currency symbol
identical for all strings?
loaded as:

char vol[30];
char cost[30];


I want to extract the "numbers" out of both the volume string and cost
string, as doubles.

What's the "best" approach?

The best approach depends on the precise format you wish to allow. If
all cost strings are in the exact format "Cost: $ " followed by a
number, then an easy way is to use strncmp to do a quick sanity check,
and to use strtod on the remainder of the string.
 
M

Malcolm McLean

philbo30 said:
Easy question, just trying to get a head start on learning a few
things...I don't need code, just looking to learn the important stuff
faster....

I have two strings:

Volume: 826100.32
Cost: $ 61243.71

loaded as:

char vol[30];
char cost[30];


I want to extract the "numbers" out of both the volume string and cost
string, as doubles.

What's the "best" approach?

Thanks again, sorry for asking such basic questions.

It depends on what you know about the input.

If you know you must have a "volume" string at this point in your program,
then write

double vol;
if( sscanf(str, "Volume: %lf", &vol) != 1)
{
/* not equal to one: string wasn't correctly set up */
}

If on the other hand you might be passed either cost or a volume string you
need to check manually.

if(!strncmp(str, "Volume:", 7))
{
}
else if(!strncmp(str, "Cost:", 5))
{
}

Sometimes it gets easier to use strtod() to pull apart a string because of
the inflexibility of ssscanf(). In this case, you must set a pointer to the
beginning of the numbers. If you know that the last character is always
either a colon or a colon followed by a dollar sign, this is not too hard to
code. However you must always be aware of malformed inputs.
 

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,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top