+ 1
How do I allow spaces to be entered using scanf()
A user can enter string but when they enter a sentence or two words with a space like "South America", scanf() just cuts off everything after "South". How do I make scanf() allow spaces?
1 Antwort
+ 2
scanf by default reads all characters till a whitespace character is read. To read spaces via scanf, you can specify a character class (specified inside []) in between % and s to specify which characters to read and which to ignore:
char str[50];
scanf("%[^\n]s", str);
The character class is supposed to contain all characters we wish to read into the string. If a character not in the character class is read, the read operation will terminate.
In this case, we use [^\n]. The ^ at the first position has a special meaning, and is used to negate the character class. When negated, the class now includes all the characters that were not part of the class and discards the characters which were part of the class. So now, scanf accepts all characters except \n.
You can also use fgets for the same purpose. This reads input till a newline is read or until the specified size is reached, with the size specified as arguments:
char str[50];
fgets(str, 50, stdin);