Design for my_gets()
Design needs
- the scanf() only gets "one word" and does NOT protect against getting
a word that it too long.
- the gets() gets an entire line but again, does NOT protect against
getting a line that is too long.
- need a function which will input a string that is guaranteed to be
no bigger than the maximum allowed size.
Design Outline
- given a character array and the maximum number of characters permitted
including the null terminator. Note: if max is 6 then up to 5 characters
can be input and the null terminator is then added for the 6th
character.
- All input should be put into the array until either a carriage return
is found or the array is full.
- If the user inputs more than the maximum number of characters, the
functions should output a message indicating the input is being
truncated since it is too long. The input stream should be cleaned
of the "extra" input.
- Put the null terminator at the end of the input characters that were
accepted.
- The function could be improved by allowing the user to input another
string if they did not like the truncation if they have overfilled the
array.
Code/Pseudocode Design
The following design does NOT give the user the option of inputting another
string if the one they input is too long and gets truncated. Your version
should do this.
void my_gets(char array, int max_chars)
{
int iochar, i = 0;
do
{
iochar = getchar();
if (iochar != '\n')
{
array[i] = iochar;
i++;
}
}
while ((iochar != '\n') && (i < max_chars - 1));
array[i] = '\0';
if (iochar != '\n')
get another character
if it is not a carriage return then give an error message and
clean the input stream.
}