How to do scanf for single char in C

The %c conversion specifier won’t automatically skip any leading whitespace, so if there’s a stray newline in the input stream (from a previous entry, for example) the scanf call will consume it immediately. One way around the problem is to put a blank space before the conversion specifier in the format string: The blank in the format string tells scanf to … Read more

Reading a string with scanf

An array “decays” into a pointer to its first element, so scanf(“%s”, string) is equivalent to scanf(“%s”, &string[0]). On the other hand, scanf(“%s”, &string) passes a pointer-to-char[256], but it points to the same place. Then scanf, when processing the tail of its argument list, will try to pull out a char *. That’s the Right Thing when you’ve passed in string or &string[0], but when … Read more

Difference between scanf() and fgets()

There are multiple differences. Two crucial ones are: fgets() can read from any open file, but scanf() only reads standard input. fgets() reads ‘a line of text’ from a file; scanf() can be used for that but also handles conversions from string to built in numeric types. Many people will use fgets() to read a line of data and then use sscanf() to dissect it.