Monday 14 October 2013

HOW to take string as a Input using getchar()

getchar() take one character as input at a time . And taking input using scanf() also has a problem that it stop taking input after encounter any space.
lets SEE an example :-
 #include<stdio.h>  
 main()  
 {  
      char str[50];  
      printf("\ninsert string press enter at end of string:\n::");  
      scanf("%s",&str);  //taking string as input
      printf("\n\n string input is ::%s",str);  //printing string
 }  
Copy this code & run you get output like this :



To solve this we can use gets() function but here We are going to take string as input using getchar() function. Remember property of getchar() :
=> getchar() take one character as input at a time.
=> getchar() stop taking input when encounter line break (enter button or '\n').

 C program :

 //use getchar() funtion to take string as input  
 #include<stdio.h>  
 main()  
 {  
      char str[50],ch;  
      int i=0;  
      printf("\n insert string & press enter key at end : ");//as getchar() stop taking input when encounter line break  
      do                           //line break means '\n' i.e enter button  
      {  
           ch=getchar();  
           str[i]=ch;  
           i++;  
      }while(ch!='\n'); // line break encounter   
      i=i-1; // as now it point last element of list is palced ='\n'  
      str[i]='\0'; // for string last element must be a '\0'  
      printf("\n\tinserted string is :\n\n::");  
      printf("%s",str);  
 }  

OUTput :

No comments:

Post a Comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets