Why scanf(“%d”, […]) does not consume ‘\n’? while scanf(“%c”) does?

It is consistent behavior, you’re just thinking about it wrong. 😉 scanf(“%c”, some_char); // reads a character from the key board. scanf(“%d”, some_int); // reads an integer from the key board. So if I do this: printf(“Insert a character: “); scanf(“%c”, &ch); // if I enter ‘f’. Really I entered ‘f’ + ‘\n’ // scanf … Read more

Whitespace before %c specification in the format specifier of scanf function in C

If you read the specification for scanf() carefully, most format specifiers skip leading white space. In Standard C, there are three that do not: %n — how many characters have been processed up to this point %[…] — scan sets %c — read a character. (POSIX adds a fourth, %C, which is equivalent to %lc.) … Read more

Why is printf with a single argument (without conversion specifiers) deprecated?

printf(“Hello World!”); is IMHO not vulnerable but consider this: const char *str; … printf(str); If str happens to point to a string containing %s format specifiers, your program will exhibit undefined behaviour (mostly a crash), whereas puts(str) will just display the string as is. Example: printf(“%s”); //undefined behaviour (mostly crash) puts(“%s”); // displays “%s\n”

Correct printf format specifier for size_t: %zu or %Iu?

MS Visual Studio didn’t support %zu printf specifier before VS2013. Starting from VS2013 (e.g. _MSC_VER >= 1800) %zu is available. As an alternative, for previous versions of Visual Studio if you are printing small values (like number of elements from std containers) you can simply cast to an int and use %d: printf(“count: %d\n”, (int)str.size()); … Read more

Platform independent size_t Format specifiers in c?

Yes: use the z length modifier: size_t size = sizeof(char); printf(“the size is %zu\n”, size); // decimal size_t (“u” for unsigned) printf(“the size is %zx\n”, size); // hex size_t The other length modifiers that are available are hh (for char), h (for short), l (for long), ll (for long long), j (for intmax_t), t (for … Read more

Using %f to print an integer variable

From the latest C11 draft: §7.16.1.1/2 …if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except for the following cases: — one type is a signed integer type, the other type is the corresponding unsigned integer type, and the … Read more

What is the purpose of the h and hh modifiers for printf?

One possible reason: for symmetry with the use of those modifiers in the formatted input functions? I know it wouldn’t be strictly necessary, but maybe there was value seen for that? Although they don’t mention the importance of symmetry for the “h” and “hh” modifiers in the C99 Rationale document, the committee does mention it … Read more

tech