If I don't know how long the word is, I cannot write char m[6];
,
The length of the word is maybe ten or twenty long.
How can I use scanf
to get input from the keyboard?
#include <stdio.h>
int main(void)
{
char m[6];
printf("please input a string with length=5\n");
scanf("%s",&m);
printf("this is the string: %s\n", m);
return 0;
}
please input a string with lenght=5
hello
this is the string: hello
With the computers of today, you can get away with allocating very large strings (hundreds of thousands of characters) while hardly making a dent in the computer's RAM usage. So I wouldn't worry too much.
However, in the old days, when memory was at a premium, the common practice was to read strings in chunks.
fgets
reads up to a maximum number of chars from the input, but leaves the rest of the input buffer intact, so you can read the rest from it however you like.in this example, I read in chunks of 200 chars, but you can use whatever chunk size you want of course.
Note that this is a simplified example with no error checking; in real life you will have to make sure the input is OK by verifying the return value of
fgets
.Also note that at the end if the readinput routine, no bytes are wasted; the string has the exact memory size it needs to have.
Safer and faster (doubling capacity) version:
Read directly into allocated space with
fgets()
.Special care is need to distinguish a successful read, end-of-file, input error and out-of memory. Proper memory management needed on EOF.
This method retains a line's
'\n'
.Sample usage
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:
The
m
between%
ands
tellsscanf()
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 tofree()
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:Note that the size of
m[]
must be at least one byte larger than the number between%
ands
.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.Enter while securing an area dynamically
E.G.
I know that I have arrived after 4 years and am too late but I think I have another way that someone can use. I had used
getchar()
Function like this:-here is the sample run for this program:-