sscanf() function is used to convert a (C) string into a series of values in program variables under the guidance of a format string which describes the values to be found in the string.
Dissecting the quoted code:
while (file >> str)
sscanf(str.c_str(), "%d", &myint);
We can assume that
file is an input stream and
str is a string. The
while loop reads one 'word' from the input into the string on each iteration, where a 'word' is a series of non-white space characters, possibly preceded by a series of white space characters.
sscanf() statement in the example has three arguments and a return value which is ignored (rather at your peril). The first argument is a C style string, so the word that was read is converted to a C string with the
str.c_str() call. The second argument is a format string which tells
sscanf() what to expect in the string. In this case, the
%d conversion specifier indicates a decimal integer. The third argument is a pointer to the corresponding type, where the converted value will be stored. In general, a format string can contain a number of conversion specifiers, and there needs to be one pointer argument for each conversion specifier that assigns (you can skip data by suppressing the assignment).
The return value from
sscanf() is the number of successful assigning conversions. In this case, you should be checking that you got one conversion completed.
Here is a working miniature program based on your example:
static void read_stuff(std::istream &file)
while (file >> str)
std::cout << "IN: <<" << str << ">>" << std::endl;
if (sscanf(str.c_str(), "%d", &myint) != 1)
std::cerr << "Oops: sscanf() failed" << std::endl;
std::cout << "GOT: " << myint << std::endl;
Suppose you type the input line:
123 234 345 abc. Then the program produces:
Oops: sscanf() failed
Note that if the names you are dealing with contain first name and surname, possibly with middle initial, and with 5 numbers (all on a single line), then you probably need a different process. You'd likely use
getline() to read a whole line, and then attempt to parse it with
sscanf() (or perhaps you'd use a
stringstream instead). You'd have to deal with fewer than 5 numbers on the line, of course. I/O is always tricky, especially when you have to deal with erroneous data too (and production-quality code always has to be ready to deal with erroneous data).