I would like to know how to read a string from Standard input of length 'n'. I tried out using fgets() function but had a problem if I submit a string of length > n
#include <stdio.h>
int STRING_SIZE=4;
int getString(char *);
int getString(char *str)
{
printf("\nEnter a string of length < %d: ", STRING_SIZE);
fgets(str, STRING_SIZE, stdin);
fflush(stdin);
printf("\n\n%s\n\n",str);
return 0;
}
int main(void)
{
char str1[1024];
char str2[1024];
getString(str1);
getString(str2);
fprintf(stdout, "%s\n", str1);
fprintf(stdout, "%s\n", str2);
return 0;
}
if I enter a string of size more than 4 for str1 then the remaining characters are getting automatically allocated to str2.
So is there a way where I can give strings to both str1, str2 even after giving string > STRING_SIZE?
I am using a GCC 4.3 compiler and if I compile above source code
$ ./a.out
Enter a string of length < 4: 12345678
123
Enter a string of length < 4:
456
123
456