In article <Bk***************@read3.inet.fi>,
Markus Ilmola <ma***********@pp.inet.fi> wrote:
How to a parse a string using C++ (standard library) same way as sscanf
in C.
For example if a have a string:
My name is "John Smith" and I'm 13 years old and 120 cm tall.
and a want to parse the name (string that can be empty (whitout the
quotation marks)), age (unsigned int) and height (unsigned int).
Using plain C I could write something like this:
char name[64];
unsigned int age, height;
sscanf(buffer, "My name is \"%[^\"]\" and I'm %u years old and %u cm
tall.");
However I want to use C++ (standard library) and I need to read the name
to a std::string (buffer is also std::string).
The following causes my compiler to barf:
int main()
{
char buffer[] = "My name is \"John Smith\" and I'm 13 years old and
120 cm tall.";
char name[64];
unsigned int age, height;
sscanf(buffer, "My name is \"%[^\"]\" and I'm %u years old and %u cm
tall.", name, age, height);
}
Are you sure you can do that with sscanf?
I'd say the easiest way to do it in C++ would be something like this:
void fn( istream& is, string& name, int& age, int& height )
{
find( istream_iterator<char>( is ), istream_iterator<char>(), '\"' );
getline( is, name, '\"' );
find( istream_iterator<string>( is ), istream_iterator<string>(),
"I'm" );
is >> age;
find( istream_iterator<string>( is ), istream_iterator<string>(),
"and" );
is >> height;
}
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.