473,466 Members | 1,382 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

parsing floats out of alphanumeric strings using strtok

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[] = "
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX YZ-+=_,!?"; // 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[i] = atof(token);
_sntprintf(buffer, sizeof(buffer) / sizeof(buffer[0]),
("%4.2f"), USERX[i]);
token = strtok (NULL, delimiters);
cout << "USERX[" << i << "]: " << USERX[i] << endl;
i++;
cout << "current buffer: " << buffer << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}

Jul 23 '05 #1
12 5579
BGP wrote:
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[] = "
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX YZ-+=_,!?"; // 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[i] = atof(token);
_sntprintf(buffer, sizeof(buffer) / sizeof(buffer[0]),
("%4.2f"), USERX[i]);
token = strtok (NULL, delimiters);
cout << "USERX[" << i << "]: " << USERX[i] << 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
Jul 23 '05 #2
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
Jul 23 '05 #3
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[] = "
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX YZ-+=_,!?"; // 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[i] = atof(token);
_sntprintf(buffer, sizeof(buffer) / sizeof(buffer[0]),
("%4.2f"), USERX[i]);
token = strtok (NULL, delimiters);
strcat (outtxt, buffer);
strcat (outtxt, " ");
//cout << "USERX[" << i << "]: " << USERX[i] << endl;
i++;
//cout << "current buffer: " << buffer << endl;
}

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

system("PAUSE");
return EXIT_SUCCESS;
}

Jul 23 '05 #4
BGP wrote:
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[] = "
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX YZ-+=_,!?"; // 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[i] = atof(token);
_sntprintf(buffer, sizeof(buffer) / sizeof(buffer[0]),
("%4.2f"), USERX[i]);

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[i] << 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::ostringstream instead of std::cout; then
pass the content of the (now formatted) std::ostringstream
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::ostringstream:
// for each double to be displayed...
{
const char * pTxt;
std::ostringstream 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
Jul 23 '05 #5
BGP
Yeah the original program I posted uses

"%4.2f"

But that clearly doesn't work. Dunno why.

Jul 23 '05 #6
BGP wrote:
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:

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


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
Jul 23 '05 #7
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.

Jul 23 '05 #8
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...

Jul 23 '05 #9


Larry I Smith wrote:
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

Jul 23 '05 #10
BGP wrote:
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

Jul 23 '05 #11
BGP wrote:
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
Jul 23 '05 #12


BGP wrote:
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

Jul 23 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Christopher Benson-Manica | last post by:
(if this is a FAQ, I apologize for not finding it) I have a C-style string that I'd like to cleanly separate into tokens (based on the '.' character) and then convert those tokens to unsigned...
18
by: Jeff Rodriguez | last post by:
If main is prototyped as: int main(int argc, char *argv); You will end up with a bunch of arguments in *argv, and the number in argc. Now what I want to do is emulate that same action on a...
6
by: Ulrich Vollenbruch | last post by:
Hi all! since I'am used to work with matlab for a long time and now have to work with c/c++, I have again some problems with the usage of strings, pointers and arrays. So please excuse my basic...
12
by: Simone Mehta | last post by:
hi All, I am parsing a CSV file. I want to read every row into a char array of reasonable size and then extract strings from it. <snippet> char foo="hello,world,bye,bye,world"; ........
8
by: netbogus | last post by:
hi, I have a file stored in memory using mmap() and I'd like to parse to read line by line. Also, there are several threads that read this buffer so I think strtok(p, "\n") wouldnt be a good...
6
by: bfowlkes | last post by:
Hello, I am trying to parse two pre-formatted text files and write them to a different files formatted in a different way. The story about this is I was hired along with about 20 other people...
19
by: pkirk25 | last post by:
I wonder if anyone has time to write a small example program based on this data or to critique my own effort? A file called Realm List.html contains the following data: Bladefist-Horde...
30
by: drhowarddrfine | last post by:
I'm working with a server that will provide me the pathname to a file, among many paths. So from getenv I may get /home/myweb/page1 but, of course, there will be many variations of that. I'm...
6
by: James Arnold | last post by:
Hello, I am new to C and I am trying to write a few small applications to get some hands-on practise! I am trying to write a random string generator, based on a masked input. For example, given...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.