I am trying to read in a variable length user input and perform some operation (like searching for a sub string within a string).
The issue is that I am not aware how large my strings (it is quite possible that the text can be 3000-4000 characters) can be.
I am attaching the sample code which I have tried and the output:
char t[],p[];
int main(int argc, char** argv) {
fflush(stdin);
printf(" enter a string\n");
scanf("%s",t);
printf(" enter a pattern\n");
scanf("%s",p);
int m=strlen(t);
int n =strlen(p);
printf(" text is %s %d pattrn is %s %d \n",t,m,p,n);
return (EXIT_SUCCESS);
}
and the output is :
enter a string
bhavya
enter a pattern
av
text is bav 3 pattrn is av 2
Don't use
scanf
orgets
for that matter because as you say, there is not real way of knowing just how long the input is going to be. Rather usefgets
usingstdin
as the last parameter.fgets
allows you to specify the maximum number of characters that should be read. You can always go back and read more if you need to.scanf(%s)
andgets
read until they find a terminating character and may well exceed the length of your buffer causing some hard to fix problems.The main problem in your case is having char arrays of unknown size. Just specify the array size on declaration.
In practice you shouldn't bother too much to be precise. Give yourself some slack to have some memory on the stack and operate on this. Once you want to pass the data further, you can use
strdup(buffer)
and have it on the heap. Know your limits. :-)Please don't ever use unsafe things like
scanf("%s")
or my personal non-favourite,gets()
- there's no way to prevent buffer overflows for things like that.You can use a safer input method such as:
You can then set the maximum size and it will detect if too much data has been entered on the line, flushing the rest of the line as well so it doesn't affect your next input operation.
You can test it with something like: