Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Read white space with scanf()

  Pi Ke        2011-09-26 11:45:43       19,784        0    

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.

 
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.

C  SCANF  WHITE SPACE  STRING FORMAT 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.