Re: sscanf with CString
Tom Serface schrieb:
I haven't used std::string much. Can you explain how this does the same
thing as the sscanf or what Joe posted. I'm sure there is some good
juju in there somewhere, but I don't see it.
Sure.
In the current C++ standard, the standard library contains new concepts for some
data types and algorithms, compared to C or MFC. One example is the concept of
strings and streams.
As opposed to MFC strings, the C++ "std:string"s do not contain any text
formating/scanning functions, just basic string manipulation. All formatting is
done using output streams, all scanning is done using input streams. Reading
from a stream is done using the overloaded operator>>(), writing is performed by
operator<<().
In most cases users first think of files when they hear about I/O streams, but
that concept is more general. A stream can be anything that implements the
stream interface (drives from basic_istream or basic_ostream).
To fill the gap of string formatting, the standard includes a set of stream
classes that read from a string or write to a string.
Now to the sample
// include the headers with the string and stringstream classes
#include <string>
#include <sstream>
// create a string stream that contains the contents
// of the recveive buffer. It delivers the characters one after
// the other when read, and returns end-of-file when the string ends
std::istringstream in(recvBuff);
// define two strings that receive the data
std::string username, password;
// read the data from the string buffer
// The operator>> is overloaded for all supported types of
// data. The operator>>(string&) reads from the stream up to the
// next white space, similar to what the %s operator in scanf does.
in >> username >> password;
What I like about the standard library is that it concentrates on the algorithm,
not the functions or the data type. All components fit nicely together.
Once you have implemented your code to read and parse data from a stream, it
works on all types of streams, even the ones that have not been invented yet.
If you create a new data type (class) that should print itself to a stream or
load from a stream, just overload the << or >> operator, and it works on all
streams. No need to create a compete set of functions like printf, sprint,
fprintf etc.
Same with the container classes. All container classes share a common interface.
Once you have written code to work on array, and later decide you need a linked
list instead, no problem. The interface for iterating, searching, remofing,
adding data is all the same.
The std library is definately worth a look.
Norbert