Parsing char array to CString

J

John Smith

Hi all,

I have a char buff[100] which contains "1234 ABCD 5678".

I can't remember what function I used before to parse the string into
individual variables. It was something like this:

forgotenFunction(var1, var2, var3, buff, "%d %s %d")

It gave me this:

var1 = "1234"
var2 = "ABCD"
var3 = "5678"

Any ideas? I will appreciate it.

J.
 
K

Kevin Goodsell

phykell said:
int sprintf(char *buffer, const char *format [,argument] ... );

Please don't top-post. Re-read section 5 of the FAQ for posting
guidelines. You might also be interested in section 3 of RFC 1855
(Netiquette Guide):

http://www.parashift.com/c++-faq-lite/
http://www.dtcc.edu/cs/rfc1855.html

Your answer is also wrong, and wouldn't be a very good suggestion even
if it wasn't. sprintf is a very dangerous function that is very
difficult to use correctly.

-Kevin
 
P

Pat McCormack

John Smith said:
Hi all,

I have a char buff[100] which contains "1234 ABCD 5678".

I can't remember what function I used before to parse the string into
individual variables. It was something like this:

forgotenFunction(var1, var2, var3, buff, "%d %s %d")

It gave me this:

var1 = "1234"
var2 = "ABCD"
var3 = "5678"

Any ideas? I will appreciate it.

J.

If you'd like to use C++ rather than C, you'd use something like;

#include <iostream>
#include <string>
#include <sstream>
int main(int argc, char* argv[])
{
std::string str("1234 ABCD 5678");
std::stringstream sstr(str);
int var1,var3;
std::string var2;
sstr >> var1 >> var2 >> var3;
std::cout<<var1<<"\n"<<var2<<"\n"<<var3<<"\n";

return 0;
}

It is a lot safer. However one advantage in sscanf is that it handles fixed
width numerics much more tidily. The stringstream operators have the notion
of delimiters hardwired in (which very strong coupling to the data I find
pretty weird in an OO library). The setwidth() manipulators only work if the
next extraction is to a string.

If you are doing lots of this stuff it is worth looking at the boost
libraries for <lexical_cast>
The old gcc stream class had stream::sscanf(). I think BSD still has this
implementation though I stand to be corrected.


Pat
 

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,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top