-
problem with fgets
Hi all, can anybody help me solve the problem below? If I enter a string with a string length of more than 10 for inputString, the next fgets will just take what is stored in the buffer. I searched the forum for problems with fgets, but only found out that if i use fgets, and if it exceeds the buff size, the next fgets will pick up what is left from the first fgets. How can I solve this? Thank you.
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
int main(void)
{
char *inputString, *inputValue;
inputString = malloc(MAXSIZE);
inputValue = malloc(MAXSIZE);
if(inputString==NULL)
{
fprintf(stderr, "Unable to allocate memory");
exit(1);
}
if(inputValue==NULL)
{
fprintf(stderr, "Unable to allocate memory");
exit(1);
}
printf("Please enter a string: ");
fgets(inputString, MAXSIZE, stdin);
printf("Input a value: ");
fgets(inputValue, MAXSIZE, stdin);
free(inputString);
free(inputValue);
return 0;
}
-
Easiest solution... you probably should increase MAXSIZE to a level you feel will help you accommodate the largest possible string that would ever be entered by the user. If you anticipate the user may sometimes enter up to 30 characters, then you should make MAXSIZE at least 31 (+1 for the NULL) for example.
Alternately, switch to using a C++ string container. They would allow strings of any arbitrary length to be entered.
-
Code:
while( fgets( buf, BUFSIZ, fp ) )
{
if( strchr( buf, '\n' ) )
break;
...otherwise, realloc some space, strcat this buffer onto it...
}
Something like that should suffice.
Quzah.
-
Ok, I got it, thanks guys!