Addresses, Pointers, Arrays and Strings - String input using the gets() library functions

Chapter chap6 section 11 The best approach to string input is to use a library function called gets(). This takes, as a single parameter, the start address of an area of memory suitable to hold the input. The complete input line is read in and stored in the memory area as a null-terminated string. Its use is shown the program below.
main()
{
/*	this program reads in strings until it has read in
	a string starting with an upper case 'z'
*/
	char	inbuf[256];	/* hope it's big enough ! */
	while(1)
	{
		printf("Enter a string ");
		gets(inbuf);
		printf("The string was >>%s<<\n",inbuf);
		if(inbuf[0] == 'Z') break;
	}
}
and a typical dialogue is shown below
$ str5
Enter a string hello world
The string was >>hello world<<
Enter a string 1
The string was >>1<<
Enter a string 
The string was >><<
Enter a string ZZ
The string was >>ZZ<<
$
We will see shortly how to use the functional value associated with gets(), this will provide a better way of terminating the input in loops such as that shown above. You should, by now, have a pretty good idea of the likely consequences of the input string being too long for the buffer area. gets() simply does not handle this problem, you can either, as is done here, declare a fairly large buffer and hope or use the more advanced function fgets() that will be described in the section on file handling.


Library functions for handling Input Strings