Addresses, Pointers, Arrays and Strings - String input using c conversion

Chapter chap6 section 10

An alternative method for the input of strings is to use scanf() with the %c conversion which may have a count associated with it. This conversion does not recognise the new-line character as special. The count specifies the number of characters to be read in. Unlike the %s and %[] ( scanset ) conversions the %c conversion does not automatically generate the string terminating NUL and strange effects will be noted if the wrong number of characters are supplied. Its use is demonstrated by the following program.

main()
{
	char	inbuf[10];
	int	i;
	while(1)
	{
		printf("Enter a string of 9 characters ");
		scanf("%10c",inbuf);
		inbuf[9]='\0';	/* Make it a string */
		printf("String was >>%s<<\n");
		if(inbuf[0] == 'Z') break;
	}
}
typical dialogue is shown below.
$ str4
Enter a string of 9 characters 123456789
String was >>123456789<<
Enter a string of 9 characters abcdefghi
String was >>abcdefghi<<
Enter a string of 9 characters abcdefghijklmnopqr
String was >>abcdefghi<<
Enter a string of 9 characters 123456789
String was >>klmnopqr
<<
Enter a string of 9 characters ttttttttt
String was >>23456789

There are some rather odd things going on here. The first point to note is that, contrary to the prompt, 10 characters are being converted. This is done so that the newline character at the end of the input line is also read in, otherwise it would be left in the input buffer to be read in as one of the input characters the next time round. The effect of providing too many input characters is that "unconsumed" input characters (including new-line characters) are left in the input buffer, these will be "consumed" by the next call to scanf(), if too few input characters are provided then scanf() hangs (or blocks ) until it has got enough input characters. Both types of behaviour can be seen in the above example.

The complexities of scanf()' s behaviour suggest that it is not really suitable for reliable general purpose string input.