Last month we looked at a simple program. This month we will look at how to do input and output in C.
C has no built in input or output commands. Functions are called that perform input and output. Last month we used the function printf. This month we will use the function getchar. Getchar gets one character from the standard input channel, the keyboard. The input from getchar is assigned to an integer variable.
The opposite function is putchar. Putchar puts one character to the standard output channel, the screen. Putchar takes in a single integer variable.
Take at look at program number 2. The program gets a character from the keyboard, then while the character is not a lower case q, the character is put to the screen and another character is read in.
This program takes characters entered from the keyboard and echos them to the screen. Getchar does not echo any characters by itself.
Any assignment can be used within an expression. Look at program number 3. With the assignment statement inside the logic of the while statement, one extra line can be left out. The assignment will be executed before the evaluation on it is performed. This shows you how C can become more compact (and more unreadable).
Since we are on the subject of input/output, let’s take a look at string input/output. C does not have a string type. You have to use an array of characters. Since there are no string types, there are no string manipulation commands. Instead there are functions to do this.
Look at program number 4. The variable string is defined as an array of 20 characters. Now a call is made to the function gets. Gets is short for “get string.” This function gets a string from the standard input and assigns it to the variable string.
Now in the while statement a comparison is made to see if the string is of length 0. Strlen is a function that will return the length of the string. If the length is greater than 0, the string is sent to the standard output with puts (put string) and another string is inputed.
A lot of necessary functions are included in the standard C library. Most commands in basic have an equal C function. Plus you may write your own functions and add them to the library. There has always been a problem that not all C libraries are equal and some programs may not be ported from compiler to compiler.
Next month we will look at how C handles files.
/* Program 2 */
#include <stdio_h>
main()
{
int c;
c = getchar();
while ( c != 'q') {
putchar(c);
c = getchar();
}
}
/* Program 3 */
#include <stdio_h>
main()
{
int c;
while ( (c = getchar() ) != 'q') {
putchar(c);
}
}
/* Prog 4 */
#include <stdio_h>
main()
{
char string[20];
gets(string);
while (strlen(string) [illegible]= 0)
puts(string);
gets(string);
}
}