Reading Strings from Terminal:



Using getchar function:

We have discussed in our previous chapter as to how to read a single character from the terminal, using the function getchar ( ). We can use this function repeatedly to read successive single characters from the input and place them into a character array. Thus, an entire line of text can be read and stored in an array. The reading is terminated when the newline character (‘\n’) is entered and the null character is then inserted at the end of the string. The getchar ( ) function call takes the form:
                        char ch;
                        ch = getchar ( );

Note that the getchar function has no perameters.

Using gets ( ) function:

Another and more convenient method of reading a string of text containing whitespaces is to use the library function gets ( ) available in the <stdio.h> header file. This is a simple function with one string parameter and called as under:
                        char address [20];
                        gets (address);
                        printf(“%s”,address);


Previous                                                                                    Next


Powered by Blogger.