What does scanf() return?
Comparing the return value with the expected count (scanf("%d %d", &a, &b) == 2) is the standard way to validate input.
C Input / Output · Exercise 1 of 4
Twelve multiple-choice questions on printf and scanf, their return values, line input, file modes, fseek, feof, text and binary mode and the standard streams. Pick an option to check your answer instantly.
What does scanf() return?
Comparing the return value with the expected count (scanf("%d %d", &a, &b) == 2) is the standard way to validate input.
Which conversion reads a value into a double variable with scanf()?
scanf receives a pointer, so it must know the exact type: %f for float *, %lf for double *, %Lf for long double *. printf uses %f for both float and double because float arguments are promoted.
Why was gets() removed from the C standard in C11?
gets takes only a pointer, so it has no idea how big the buffer is. fgets(buf, sizeof buf, stdin) is the safe replacement.
When the line fits in the buffer, what does fgets() do with the newline character?
fgets stores the newline, which also tells you a complete line was read. Remove it with buf[strcspn(buf, "\n")] = '\0';.
What are stdin, stdout and stderr?
They are macros for FILE * values, so they can be passed to any stdio function: fprintf(stderr, …), fgets(buf, n, stdin). File descriptors 0, 1, 2 belong to POSIX, not to C.
You want to add log lines to the end of a file, creating it if it does not exist. Which mode?
"a" creates the file if needed, and every write goes to the end even after an fseek. "w" would destroy the existing contents; "r" and "r+" fail if the file is missing.
What does fseek(fp, -3L, SEEK_END); do?
The offset is added to the origin. With SEEK_END the origin is the end of the file, so a negative offset moves backwards from it. Use SEEK_CUR for a move relative to the current position.
When does feof(fp) return a non-zero value?
The end-of-file indicator is set by a read that fails. That is why while (!feof(fp)) runs one extra time; test the read function's result instead.
Which call correctly opens photo.jpg to read its bytes?
Non-text data must be opened in binary mode so that no line-ending translation happens. On Windows "r" could corrupt the bytes; "rb" is correct everywhere.
In scanf("%*d %d", &x);, what does the * do?
In scanf, * suppresses assignment and the item is not counted in the return value. scanf has no way to take a width from an argument.
Timed online tests with instant scores and explanations.