I've seen only one simple way of reading an arbitrarily long string, but I've never used it. I think it goes like this:
char *m = NULL;
printf("please input a string\n");
scanf("%ms",&m);
if (m == NULL)
fprintf(stderr, "That string was too long!\n");
else
{
printf("this is the string %s\n",m);
/* ... any other use of m */
free(m);
}
The m
between %
and s
tells scanf()
to measure the string and allocate memory for it and copy the string into that, and to store the address of that allocated memory in the corresponding argument. Once you're done with it you have to free()
it.
This isn't supported on every implementation of scanf()
, though.
As others have pointed out, the easiest solution is to set a limit on the length of the input. If you still want to use scanf()
then you can do so this way:
char m[100];
scanf("%99s",&m);
Note that the size of m[]
must be at least one byte larger than the number between %
and s
.
If the string entered is longer than 99, then the remaining characters will wait to be read by another call or by the rest of the format string passed to scanf()
.
Generally scanf()
is not recommended for handling user input. It's best applied to basic structured text files that were created by another application. Even then, you must be aware that the input might not be formatted as you expect, as somebody might have interfered with it to try to break your program.