parsing floats out of alphanumeric strings using strtok

B

BGP

I am working on a WIN32 API app using devc++4992 that will accept Dow
Jones/NASDAQ/etc. stock prices as input, parse them, and do things with
it. The user can just cut and paste back prices into a window and hit
a button to process it.

The information thus enters the program as a char array. Prices can be
between $1 and $100, including cents. So we can have prices such as
3.01, 1.56, 11.57, etc. The char array is an alphanumeric string, so
everything that isn't x.xx or xx.xx has to be parsed out.

Once a number gets parsed out, it gets stored in an array for later
use. Eventually, we will display the numbers later, and they must be
in the same two decimal places format.

I am having a terrible time getting the actual API to work. When it
reads data it can get stuck in the loop forever, seemingly never
hitting a NULL. I stripped it down and wrote this small console app to
try to figure out where it is going wrong. Surprise, this app seems to
work without being stuck in a loop.

There is one problem here I can't seem to fix. The buffer should
display the number to two decimal places, but its not doing so. I've
been trying to figure this out for six hours or so and I thought I'd
ask here. When this program is run, the current buffer should display
to two decimal places... Thanks in advance.

#include <cstdlib>
#include <iostream>
#include <math.h>
#include <tchar.h>

using namespace std;

int main(int argc, char *argv[])
{
char rawtxt[] = "parse this 3.50now 4.00 5.67", outtxt[] = "",
temptxt[] = "", buffer[] ="";
int i = 0;
float USERX[5000];
const char delimiters[] = "
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+=_,!?"; // parse
tchar string by splitting when these chars are found.
char* token;

token = strtok (rawtxt, delimiters); // cut first back price out
of rawtxt

cout << "This program should parse a string into numbers with
decimals." << endl << endl;
cout << "string to parse: " << rawtxt << endl << endl;

while (token != NULL)
{
cout << "current token: " << token << endl;
USERX = atof(token);
_sntprintf(buffer, sizeof(buffer) / sizeof(buffer[0]),
("%4.2f"), USERX);
token = strtok (NULL, delimiters);
cout << "USERX[" << i << "]: " << USERX << endl;
i++;
cout << "current buffer: " << buffer << endl;
}


system("PAUSE");
return EXIT_SUCCESS;
}
 
L

Larry I Smith

BGP said:
I am working on a WIN32 API app using devc++4992 that will accept Dow
Jones/NASDAQ/etc. stock prices as input, parse them, and do things with
it. The user can just cut and paste back prices into a window and hit
a button to process it.

The information thus enters the program as a char array. Prices can be
between $1 and $100, including cents. So we can have prices such as
3.01, 1.56, 11.57, etc. The char array is an alphanumeric string, so
everything that isn't x.xx or xx.xx has to be parsed out.

Once a number gets parsed out, it gets stored in an array for later
use. Eventually, we will display the numbers later, and they must be
in the same two decimal places format.

I am having a terrible time getting the actual API to work. When it
reads data it can get stuck in the loop forever, seemingly never
hitting a NULL. I stripped it down and wrote this small console app to
try to figure out where it is going wrong. Surprise, this app seems to
work without being stuck in a loop.

There is one problem here I can't seem to fix. The buffer should
display the number to two decimal places, but its not doing so. I've
been trying to figure this out for six hours or so and I thought I'd
ask here. When this program is run, the current buffer should display
to two decimal places... Thanks in advance.

#include <cstdlib>
#include <iostream>
#include <math.h>
#include <tchar.h>

using namespace std;

int main(int argc, char *argv[])
{
char rawtxt[] = "parse this 3.50now 4.00 5.67", outtxt[] = "",
temptxt[] = "", buffer[] ="";
int i = 0;
float USERX[5000];
const char delimiters[] = "
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+=_,!?"; // parse
tchar string by splitting when these chars are found.
char* token;

token = strtok (rawtxt, delimiters); // cut first back price out
of rawtxt

cout << "This program should parse a string into numbers with
decimals." << endl << endl;
cout << "string to parse: " << rawtxt << endl << endl;

while (token != NULL)
{
cout << "current token: " << token << endl;
USERX = atof(token);
_sntprintf(buffer, sizeof(buffer) / sizeof(buffer[0]),
("%4.2f"), USERX);
token = strtok (NULL, delimiters);
cout << "USERX[" << i << "]: " << USERX << endl;
i++;
cout << "current buffer: " << buffer << endl;
}


system("PAUSE");
return EXIT_SUCCESS;
}



Here's one way (of many) to do it:

#include <iostream>
#include <sstream>

int main()
{
// text used to test the parsing logic.
// output should be: 5.00 -6.00 3.50 4.00 5.67 0.30
char * rawtxt = "parse a5b-6 this 3.50now 4.00 5.67 b.3";

// create the input stream 'is' from the test text
std::istringstream is(rawtxt);

// save the current precision of 'cout' in 'ss'
std::streamsize ss = std::cout.precision();

// set the precision of 'cout' to 2 decimal positions
std::cout.precision(2);

// set 'cout' to 'fixed' mode - causes extra
// trailing zeroes if req'd (e.g. 0.20)
std::cout << std::fixed;

// while no error on input stream 'is'
while (is)
{
std::string aWord;

// if we read the next whitespace-delimited "word"
// from 'is' into 'aWord'. Note: 'aWord' will
// auto-expand its storage as req'd.
if (is >> aWord)
{
double d = 0;

// make the input stream 'num' from the text
// in 'aWord'
std::istringstream num(aWord);

// while no errors on input stream 'num'
while (num)
{
// skip any leading alpha chars in 'num'
while (std::isalpha(num.peek()))
num.get();

// if any error on input stream 'num',
// loop to get the next "word" from 'is'
if (!num)
break;

// if we can read a double into 'd'
// from input stream 'num'
if (num >> d)
{
// print the double 'd' with 2 fixed
// decimal positions
std::cout << "d = "
<< d << std::endl;
}
}
}
}

// restore the original precision of 'cout'.
// this is not req'd when exiting the program,
// but might be required otherwise
std::cout.precision(ss);

return 0;
}

Regards,
Larry
 
L

Larry I Smith

Larry I Smith wrote:
[snip]
// restore the original precision of 'cout'.
// this is not req'd when exiting the program,
// but might be required otherwise
std::cout.precision(ss);

// also clear the 'fixed' flag from 'cout'
std::cout.unsetf(std::ios_base::fixed);
return 0;
}

Regards,
Larry

Oops, I forgot to include the line to clear the 'fixed'
flag on 'cout' (see the embedded line added above).
This is not req'd when exiting, but might be req'd otherwise.

Larry
 
B

BGP

This can't be a cout manipulation...

The output is going to be sent to a string and then to an edit control
in the WIN32 API.

I'm only using cout as a conveinence to make it easier to see my
problem.

Maybe this is a better example:

#include <cstdlib>
#include <iostream>
#include <math.h>
#include <tchar.h>

using namespace std;

int main(int argc, char *argv[])
{
char rawtxt[] = "parse this 3.50now 4.00 5.67", outtxt[] = "",
temptxt[] = "", buffer[] ="";
int i = 0;
float USERX[5000];
const char delimiters[] = "
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+=_,!?"; // parse
tchar string by splitting when these chars are found.
char* token;

token = strtok (rawtxt, delimiters); // cut first back price out
of rawtxt

cout << "This program should parse a string into numbers with
decimals." << endl << endl;
cout << "string to parse: " << rawtxt << endl << endl;

while (token != NULL)
{
cout << "current token: " << token << endl;
USERX = atof(token);
_sntprintf(buffer, sizeof(buffer) / sizeof(buffer[0]),
("%4.2f"), USERX);
token = strtok (NULL, delimiters);
strcat (outtxt, buffer);
strcat (outtxt, " ");
//cout << "USERX[" << i << "]: " << USERX << endl;
i++;
//cout << "current buffer: " << buffer << endl;
}

cout << "buffer results: " << outtxt << endl;g

system("PAUSE");
return EXIT_SUCCESS;
}
 
L

Larry I Smith

BGP said:
This can't be a cout manipulation...

The output is going to be sent to a string and then to an edit control
in the WIN32 API.

I'm only using cout as a conveinence to make it easier to see my
problem.

Maybe this is a better example:

#include <cstdlib>
#include <iostream>
#include <math.h>
#include <tchar.h>

using namespace std;

int main(int argc, char *argv[])
{
char rawtxt[] = "parse this 3.50now 4.00 5.67", outtxt[] = "",
temptxt[] = "", buffer[] ="";
int i = 0;
float USERX[5000];
const char delimiters[] = "
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+=_,!?"; // parse
tchar string by splitting when these chars are found.
char* token;

token = strtok (rawtxt, delimiters); // cut first back price out
of rawtxt

cout << "This program should parse a string into numbers with
decimals." << endl << endl;
cout << "string to parse: " << rawtxt << endl << endl;

while (token != NULL)
{
cout << "current token: " << token << endl;
USERX = atof(token);
_sntprintf(buffer, sizeof(buffer) / sizeof(buffer[0]),
("%4.2f"), USERX);



The above line won't work. 'buffer[]' is a zero length char array
on the stack. using it as the destination for any *printf()
function will cause unpredictable results - you'll overwrite the
data on the stack that 'follows' 'buffer[]'.

token = strtok (NULL, delimiters);
strcat (outtxt, buffer);
strcat (outtxt, " ");
//cout << "USERX[" << i << "]: " << USERX << endl;
i++;
//cout << "current buffer: " << buffer << endl;
}

cout << "buffer results: " << outtxt << endl;g

system("PAUSE");
return EXIT_SUCCESS;
}


Hmm, I guess I don't understand your problem...

The example I gave you can be applied to any stream,
not just 'cout'.

Do you want to store the numbers parsed from the string as
binary doubles (e.g. 9.5) or as text strings (e.g. "9.50")?

Your 'USERX[]' is an array of 'floats' In the real program
will you being storing floats (or doubles) in an array like
that until you display them? If that is the case, the only
way you can affect the display format (e.g. "9.50" instead
of "9.5") is to format each number into a string, then
display that string WHEN YOU ARE READY TO DISPLAY THE NUMBER.

My example shows one way to do that - except in your case
you could use std::eek:stringstream instead of std::cout; then
pass the content of the (now formatted) std::eek:stringstream
to the display logic. Or you could use sprintf().

An example using sprintf():

char buf[16];

// for each double to be displayed...
{
// get the double into 'd' somehow...

// format the double into buf[]
sprintf(buf, "%4.2f", d);

// display the formatted number in buf[] on the screen...

// loop to process the next double
}

An example using std::eek:stringstream:


// for each double to be displayed...
{
const char * pTxt;
std::eek:stringstream os;
os.precision(2);
os << std::fixed;

// get the double into 'd' somehow...

// format the double into 'os'
os << d;

// get a pointer to the formatted number
pTxt = os.str().c_str();

// display the formatted number at *pTxt on the screen...

// loop to process the next double
}

Regards,
Larry
 
B

BGP

Yeah the original program I posted uses

"%4.2f"

But that clearly doesn't work. Dunno why.
 
L

Larry I Smith

BGP said:
Yeah the original program I posted uses

"%4.2f"

But that clearly doesn't work. Dunno why.

Hmm, I answered that already. Here's a quote
from my earlier post:

_sntprintf(buffer, sizeof(buffer) / sizeof(buffer[0]),
("%4.2f"), USERX);




The above line won't work. 'buffer[]' is a zero length char array
on the stack. using it as the destination for any *printf()
function will cause unpredictable results - you'll overwrite the
data on the stack that 'follows' 'buffer[]'.

</quote>

It's time for you to get some basic C/C++ training...

Regards,
Larry
 
B

BGP

That last comment was uncalled for and rude. May karma bring that
comment back on you threefold in your life. You need to be cut down a
few pegs.

Its more like I'm a bit rusty in C/C++ which is why I come here to ask
questions.

I learned it about ten years ago or so. Since then I did a lot of
programming in javascript or QBASIC or other things. I'm coming back
to it again and trying to figure stuff out, like asking on this forum.
 
B

BGP

Thank you for the help tho.

I seem to be getting the results I wanted. Yay!

Now to see if I can get it working in the WIN32 API...
 
D

Default User

Larry said:
char rawtxt[] = "parse this 3.50now 4.00 5.67", outtxt[] = "",
temptxt[] = "", buffer[] ="";

The above line won't work. 'buffer[]' is a zero length char array
on the stack. using it as the destination for any *printf()
function will cause unpredictable results - you'll overwrite the
data on the stack that 'follows' 'buffer[]'.

Small nitpick, it's of size 1.


Brian
 
L

Larry I Smith

BGP said:
That last comment was uncalled for and rude. May karma bring that
comment back on you threefold in your life. You need to be cut down a
few pegs.

Its more like I'm a bit rusty in C/C++ which is why I come here to ask
questions.

I learned it about ten years ago or so. Since then I did a lot of
programming in javascript or QBASIC or other things. I'm coming back
to it again and trying to figure stuff out, like asking on this forum.

It wasn't meant to be rude - just an opinion based
on the basic errors in the example code you provided...

Enough now.

Regards,
Larry
 
L

Larry I Smith

BGP said:
Thank you for the help tho.

I seem to be getting the results I wanted. Yay!

Now to see if I can get it working in the WIN32 API...

Tip of the day:

character arrays (e.g. char[]) do not auto-expand;
their size is fixed. examples:

char c1[3]; // fixed size of 3
char c2[] = "hello"; // fixed size of 6 , includes nul-terminator

std::string variables can expand. examples:

std::string s1 = "hello"; // s1.length() == 5
std::string s2; // s2.length() == 0

s2 = "BGP"; // s2.length() == 3
s1 += ' '; // s1.length() == 6
s1 += s2; // s1.length() == 9, "hello BGP"

const char * cStr = s1.c_str(); // *cStr = "hello BGP"
// strlen(cStr) == 9

Larry
 
D

Default User

BGP said:
Yeah the original program I posted uses

"%4.2f"

But that clearly doesn't work. Dunno why.


Please quote a relevant portion of the previous message when replying.
To do so from the Google interface, don't use the Reply at the bottom
of the message. Instead, click "show options" and use the Reply shown
in the expanded headers.

Brian
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top