The following function creates a new text file and allows the user to input text to be saved to the file. The main issues that I\'m having troubles fixing is 1)allowing spaces b
Use fgets() instead of scanf()
to get the input text from the user.
To do so replace this line
scanf("%s", c);
with the following code:
if (NULL != fgets(c, sizeof(c), stdin))
{
fprintf(pf, "%s", c);
}
else
{
if (0 != ferror(stdin))
{
fprintf(stderr, "An error occured while reading from stdin\n");
}
else
{
fprintf(stderr, "EOF was reached while trying to read from stdin\n");
}
}
To allow the user to read in more then one line put a loop around the code above. Doing so you need to define a condition which tells the program to stop looping:
The following example stops reading in lines when entering a single dot "." and pressing return:
do
{
if (NULL != fgets(c, sizeof(c), stdin))
{
if (0 == strcmp(c, ".\n")) /* Might be necessary to use ".\r\n" if on windows. */
{
break;
}
fprintf(pf, "%s", c);
}
else
{
if (0 != ferror(stdin))
{
fprintf(stderr, "An error occured while reading from stdin\n");
}
else
{
fprintf(stderr, "EOF was reached while trying to read from stdin\n");
}
break;
}
} while (1);