This program can read a line of text (up to a maximum of 80 characters) into the string line using getchar function. Every time a character is read, it is assigned to its location in the string line and then tested for newline character. When the new line character is read (signalling the end of line), the reading loop is terminated and the new line character is replaced by the null character to indicate the end of character string.
When the loop is exited, the value of the index is one number higher than the last character position in the string (since it has been incremented after assigning the new character to the string). Therefore the index value c-1 gives the position where the null character is to be stored.
PROGRAM
#include <stdio.h>
main ( )
{
char line [81], character ;
int c ;
c = 0 ;
printf ("Enter text. Press <Return> at end\n") ;
do
{
character = getchar ( ) ;
line [c] = character ;
c++ ;
}
while (character ! = '\n') ;
c = c - 1 ;
line [c] = '\0' ;
printf ("\n%s\n", line) ;
}
Output: Enter text. Press <Return> at end
Programming in C is interesting.
Programming in C is interesting.
Enter text. Press <Return> at end
National Centre for Expert Systems, Hyderabad.
National Center for Expert Systems, Hyderabad.
No comments:
Post a Comment