The scanf family reads text and converts it according to format specifiers. A wrong specifier can cause undefined behavior or incorrect data, while a complex format string can be difficult to read. section 6.1
Watch for format-string surprises:
- %d means decimal, %i can interpret a number with a leading zero as octal, and reading a double requires %lf. section 6.1
- When legacy constraints require scanf-style functions, check specifiers carefully; typed extraction with std::istringstream offers a more readable alternative. section 6.1
Listing 6.1 Using complicated format specifiers to determine conversions
int main() {
const char* str = "3.14159 042 boxes .3";
double pi;
int cats;
int mice;
char buffer[5];
int count = sscanf(str, "%lf%*c%i%s%d", &pi, &cats,
buffer, &mice); #1
if (count != 4) #2
std::cout << "error reading value " << count+1 << '\n';
printf("%f being eaten by %d cats in %s along with %d mice\n",
pi, cats, mice, mice); #3
return 0;
}
A complex sscanf format string illustrates how several conversions can be packed into one difficult-to-parse expression. section 6.1
Listing 6.2 Using types to determine conversions
int main() {
std::istringstream str("3.14159 042 boxes .3");
double pi;
int cats;
int mice;
std::string buffer;
str >> pi; #1
if (str.fail())
std::cout << "error reading value 1\n";
str >> cats;
if (str.fail())
std::cout << "error reading value 2\n";
str >> buffer;
if (str.fail())
std::cout << "error reading value 3\n";
str >> mice;
if (str.fail())
std::cout << "error reading value 4\n";
std::cout << pi << " being eaten by " << cats << " cats in " << mice
<< " along with " << mice << " mice\n"; #2
return 0;
}
Typed extraction from a string stream shows the alternative approach, with a separate failure check after each value. section 6.1
