473,666 Members | 2,357 Online
Bytes | Software Development & Data Engineering Community
+ 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[] = "
abcdefghijklmno pqrstuvwxyzABCD EFGHIJKLMNOPQRS TUVWXYZ-+=_,!?"; // 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(buff er, 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 5606
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[] = "
abcdefghijklmno pqrstuvwxyzABCD EFGHIJKLMNOPQRS TUVWXYZ-+=_,!?"; // 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(buff er, 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::istringstr eam is(rawtxt);

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

// set the precision of 'cout' to 2 decimal positions
std::cout.preci sion(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::istringstr eam num(aWord);

// while no errors on input stream 'num'
while (num)
{
// skip any leading alpha chars in 'num'
while (std::isalpha(n um.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.preci sion(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.preci sion(ss);
// also clear the 'fixed' flag from 'cout'
std::cout.unset f(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[] = "
abcdefghijklmno pqrstuvwxyzABCD EFGHIJKLMNOPQRS TUVWXYZ-+=_,!?"; // 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(buff er, 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[] = "
abcdefghijklmno pqrstuvwxyzABCD EFGHIJKLMNOPQRS TUVWXYZ-+=_,!?"; // 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(buff er, 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::ostringstr eam instead of std::cout; then
pass the content of the (now formatted) std::ostringstr eam
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::ostringstr eam:
// for each double to be displayed...
{
const char * pTxt;
std::ostringstr eam 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(buff er, 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

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

Similar topics

10
2625
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 integers. What is the best standard(!) C++ way to accomplish this? -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
18
1957
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 string. Say for example I have: char *command = "./blah --arg1 --arg2 123 -x --arg2=w00t" How do I acheive the same effect as in main()?
6
2115
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 question: I want to parse a string like "3.12" to get two integers 3 and 12. I wanted to use the function STRTOK() I wrote a main- and a subfunction like: main() {
12
8711
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"; ..... sscanf(foo,"%s%*%s%*%s%*%s%*%s",s1,s2,s3,s4,s5); <snippet/> This is giving me junk .
8
2813
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 choice. I'd like to hear from you guys what would be a good implementation in this case. thanks in advance,
6
2710
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 and it seems we are trying to learn the whole C language in two weeks! To top it all off, I was an English Major, but I'm trying my best. Ok back to the program. So we have two files product_catalog.txt and sales_month.txt The info in...
19
3097
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 Nordrassil-Horde Draenor-Alliance Nordrassil-Alliance Nordrassil-Neutral Draenor-Horde
30
8148
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 unsure of the best way to go about following the path. Should I read one char at a time or use scanf? The problem could occur with something like /home/mypage/page1/page1/page2/page2, for example. I have not been programming in a few years so I...
6
3507
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 the string: "AAANN" it would return a string containing 3 alphanumeric characters followed by 3 digits. This part I have managed:) I would now like to add some complexity to this, such as repetitions and grouping. For example, I'd like to have...
0
8352
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8863
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8780
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8549
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8636
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7378
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6189
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
2005
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.