Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

Technical Article => Programming =>  C

Read white space with scanf()

  Pi Ke      2011-09-26 11:45:43      4,924    0    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

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious

  RELATED


  0 COMMENT


No comment for this article.


  WRITE ARTICLE

What is HTML5?

By sonic0002
How to tell HTML from HTML5? Follow below steps: Try it out on Internet Explorer Did it work? No? It's HTML5