Read A String

This is a pair exercise and must be competed in your tutorial or lab with your partner.

In the next few activities, you’ll be building some functions that deal with strings.

Remember that a string is an array of characters, where the last character is followed by the character \0, which we refer to as the null terminator.

For this activity, you’ll be writing the function readLine.

void readLine (int bufferLen, char *buffer);

It takes an array, which we call a “buffer”, the size of that array, and reads a line of text from standard input into the buffer. For our purposes, a line of text will always end with the newline character, \n; you should not write the newline into the buffer.

If more characters are available to be read than there is array space to read it into, you should stop after you have filled the array.

You should never lose characters, except for the newline.

You should always make sure that, when your function returns, you have null-terminated the buffer.

We’ve provided a simple main function which calls the readLine function and prints out the resulting buffer.

Download readLine.c, or copy it into your current directory on a CSE system by running

$ cp /web/cs1511/17s2/week05/files/readLine.c .

If you’re uncertain about where to start, you may like to try the Parrot, String Length, and Array Functions warm-up activities.

To run some simple automated tests:

$ 1511 autotest readLine

To run Styl-o-matic:

$ 1511 stylomatic readLine.c
Looks good!

You’ll get advice if you need to make changes to your code.

Submit your work with the give command, like so:

$ give cs1511 wk05_readLine

Or, if you are working from home, upload the relevant file(s) to the wk05_readLine activity on Give Online.