Tuesday, July 3, 2012

Can you read a space with scanf? - C GNU/Win

If you are a student, and you are learning C, your teacher would have thought you that scanf can't read spaces as it treats spaces as line breakers. But It's not actually like that. See,

#include<stdio.h>
void main(void)
 {
  char line[32];
  printf("Enter a Text with Space :");
  scanf("%s",line);
  printf("\n\nReceived Text : %s",line);
 }

Output:
        Enter a Text with Space : Sibi Dharan
        Received Text : Sibi


 As I already said, this is because scanf("%s",<--(char[])-->); treats space as a string terminator.


Now look at this.

#include<stdio.h>
void main(void)
 {
  char line[32];
  printf("Enter a Text with Space :");
  scanf("%[^\n]s",line);  //this is explained below
  printf("\n\nReceived Text : %s",line);
 }

Output:
        Enter a Text with Space : Sibi Dharan
        Received TextSibi Dharan



This is because, the latter treats the space as space itself  and the stream continues to receive the characters until '\n' is received and this is represented within square braces. Suppose if '\n' is replaced with '\t', the stream continues to receive the characters until tab is pressed. For our objective, '\n' is good for use.



Be free for commenting your doubts.

2 comments: