Programming in C

(Barry) #1
Variable-Length Character Strings 209

Also available from the function library is a function called gets.The sole purpose of
this function—you guessed it—is to read in a single line of text. As an interesting pro-
gram exercise, Program 10.6 shows how a function similar to the getsfunction—called
readLinehere—can be developed using the getcharfunction.The function takes a sin-
gle argument: a character array in which the line of text is to be stored. Characters read
from the terminal window up to, but not including, the newline character are stored in
this array by the function.


Program 10.6 Reading Lines of Data


#include <stdio.h>


int main (void)
{
int i;
char line[81];
void readLine (char buffer[]);


for ( i = 0; i < 3; ++i )
{
readLine (line);
printf ("%s\n\n", line);
}

return 0;
}


// Function to read a line of text from the terminal


void readLine (char buffer[])
{
char character;
int i = 0;


do
{
character = getchar ();
buffer[i] = character;
++i;
}
while ( character != '\n' );

buffer[i - 1] = '\0';
}

Free download pdf