Usually, when we want to enter string with white spaces in C, we need to call gets() or fgets(0 method. We usually will not use scanf(0 or fscanf() because they cannot accept white spaces when scan user inputs.
Read white space with scanf()
Summary
While `scanf()` and `fscanf()` typically do not read strings containing whitespace, a specific format specifier allows them to do so. Developers can use `"%[^\n]s"` within `fscanf()` to read all characters, including spaces, until a newline character is encountered. This regex-like `[^\n]` expression matches any character except the newline, and a character limit can also be specified. However, it is important to note that `scanf()` and `gets()` are not recommended for user input due to their lack of buffer overflow checks, with `fgets()` being the safer alternative.
But when we specify the format in scanf() function, we may read strings with white space. the code section below illustrate this:
#include <stdio.h>
int main(int argc,char **argv){
char name[30];
fprintf(stdout,"Please enter the name : \n");
fscanf(stdin,"%[^\n]s",name);
fprintf(stdout,"%s\n",name);
return 0;
}
On above code snippet, the line fscanf(stdin,"%[^\n]s",name); can be used to accept strings with white space. Here [^\n] is regular expression like format expression, it means that the fscanf(0 method can accept any character except the new line. Also, we can specify how many characters to scan from user.
Anyway, in programming we donot recommend use scanf() and gets() to read string from user because they donot have buffer overflow check. We can use fgets() instead.
No comment for this article.