scanf() is a general purpose console input routine.
To read a string “%s” format specifier is used.
scanf() reads a string until the first “white space” character is encountered. below is the list of “white space” characters:
- space
- tab (\t)
- vertical tab (\v)
- form feed (\f)
Example 1:
#include int main() { char str[10]; printf("Enter string with space:\n"); scanf("%s", str); printf("String entered is:\n", str); return 0; }
Output:
Enter string with space: Binary Rambo String entered is: Binary
The above output is missing portion of the string (Rambo) entered, as there is a space between word “Binary” and “Rambo”.
To read a string with space in between, scan set ( %[] ) format specifier needs to be used.
Example 2:
#include int main() { char str[10]; printf("Enter string with space:\n"); scanf("%[^\n]s", str); printf("String entered is:\n", str); return 0; }
Output:
Enter string with space: Binary Rambo String entered is: Binary Rambo
The above output prints the complete string entered, because of the scan set format specifier which is instructing to read a string until a new line (\n) is not (^) encountered.