There is one last thing to worry about - That's the return value from fgets -> If this is NULL, there is a big problem. I've implemented this with a return value. [edit] It would also be worth mentioning the return value from malloc should not be NULL [/edit]
If you want to test if it is working, change stdin to stdout
Code:
char *get_user_input (char *prompt, char *input_string, size_t input_string_size);
int main(void)
{
char *fname;
if ((fname = malloc(MAXNAME * sizeof(*fname))) == NULL)
{
fprintf(stderr, "-ERROR-\nAllocation Failure\n");
return EXIT_FAILURE;
}
if (get_user_input ("Enter first name", fname, MAXNAME) != NULL)
{
printf("Name is %s\n", fname);
}
else
{
fprintf(stderr, "-ERROR-\nProblem with reading string\n");
return EXIT_FAILURE;
}
free(fname);
return EXIT_SUCCESS;
}
char *get_user_input (char *prompt, char *input_string, size_t input_string_size)
{
int read_ok;
char *return_val;
do
{
char *s;
printf("%s: ", prompt);
fflush(stdout);
if ((return_val = fgets(input_string, input_string_size, stdin)) == NULL)
{
break;
}
if ((s=strstr(input_string, "\n")) != NULL)
{
*s = '\0';
read_ok = 1;
}
else
{
int c;
while((c = getchar()) != '\n' && c != EOF)
{
continue;
}
fprintf(stderr, "Problem with string size\n");
read_ok = 0;
}
}
while (read_ok == 0);
return return_val;
}