scanf

This is like the input() command in python, with a few differences. scanf is essentially matching input to the right conversion specifications. scanf(format string, address of variable to store in); e.g. scanf("%f",&x);

If we want the input to look a certain way, we can. Consider scanf("%d/%d,&x,&y); The input can be 5/ 96 but not 5 / 96 (pay attention to the spaces)

whitespace in format strings

One or more whitespace characters in the format string (the first arg of the scanf function), will match zero or more whitespace characeters in the input.

As it searches for the beginning of a number it by default ignores whitespace characters.

But it does not by default ignore whitespaces before another character, like "%d/"

What is wrong with scanf("%d ",&x)?

Leaving a \n or trailing whitespace can cause scanf to “skip whitespace, read an integer, then skip to the next non-white-space characer. A format string like this can cause an interactive program to”hang” until the user enters a nonblank character.”

scanf for a double, or long double

for a double, scanf("%lf",&d);, scanf("%le",&d); or, scanf("%lg",&d); for a long double, scanf("%Lf",&d);, scanf("%Le",&d); or, scanf("%Lg",&d);

scanf a character, and caveats

scanf("%c", &ch);, note this does not allow 0 or more whitespace characters. For that via inspection do scanf(" %c", &ch); getchar

scanf a string

see basic_data_type

backlinks