I have a challenge: ask user to input first, the maximum number of characters, then, input the string. Memory should be dynamically allocated and the string inputted should be printed.
My code;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int size;
char * pText = NULL;
// get the maximum string length
printf("\nEnter maximum length of string (a number): ");
scanf("%d", &size);
// allocate memory
pText = (char *)malloc(size * sizeof(char));
if(pText != NULL)
{
// get user's input string
printf("\nEnter your string:\n");
fgets(pText, size, stdin);
printf("\nThe input string is %s.\n", pText);
}
free(pText);
return 0;
}
This is all the code that there is. The problem I am experiencing is in the if-block; the originally implemented code is,
scanf(" ");
gets(pText);
printf("\nThe inputted string is %s.\n", *pText);
which is some wizardry that I believe removes terminating characters from scanf
, enabling gets
to read in a string along with terminating character (if I have the information correct); it has not been fully explained. While that implementation works, I have been told that it is possible to use fgets
to implement the same functionality.
My attempt to implement fgets
leads to the outcome where the user cannot input a string because the program terminates after the maximum number of characters (as an integer) has been entered and <return>
has been pressed. I believe that because pText IS NULL, or zero, the program terminates before any text can be written.
I have tried reading around the subject of fgets
, but most examples deal with accepting data from an input file, not stdin
. I'm not sure what the problem is, or where I am going wrong, but I would appreciate some enlightenment.