Naltroc
Naltroc

Reputation: 1007

Write user input string to file in C

My program needs to take a user's input and save it to an external file for future reference. Here is the basic outline of the code.

void newActivity(FILE *foutput) {
    char name[31];
    char description[141];
    finput = fopen("activities.txt", "a");

    printf("\n What is the name of your activity (up to 30 characters):\n");
    fgets(name, sizeof(name), stdin);

    printf("\nEnter a brief description (up to 140 characters) of what %s is about:\n",
           fputs(name, stdout));
    fgets(description, sizeof(description), stdin);

    if (finput == NULL) {
        printf("\nCould not open file.");
        exit(1);
    }

    fprintf(foutfile, "%s\n", name);
    fprintf(foutfile, "%s\n", description);

    fclose(foutfile)
}

When I run a simple test program that only asks for a name and prints that name, all is good. It looks like this:

int main() {
    char name[50];
    fprint("What is your name? ");
    fgets(name, sizeof(name), stdin);
    fputs(name, stdout);
    return 0;
}

Unlike the working test program, my program does not not take any input from the user before moving to the second printf() statement. It does read the strings within the printf statements, but return a value of (null).

As for writing to the file, the two fprintf lines should do it, but I cannot confirm it as the input text has not been properly recorded.

This is a function declared outside of my main(). Does that make affect the situation?

Upvotes: 3

Views: 6031

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

This is incorrect:

printf("\nEnter a brief description (up to 140 characters) of what %s is about:\n", fputs(name, stdout));

fputs returns an int, while your printf wants a string %s.

Remove fputs, and pass name to printf instead:

printf("\nEnter a brief description (up to 140 characters) of what %s is about:\n", name);

Use %s when writing out the string to a file:

fprintf(foutfile, "%s", name);
fprintf(foutfile, "%s", description);

Note that you don't need \n, because fgets keeps \n with the string.

From the comments: My concern is why the program is failing to [read input] for fgets(name, sizeof(name), stdin)

This commonly happens when your stdin has an extra \n lingering from a previous operation. For example, if your previous input operation has been reading of an int using scanf, you would see this effect:

scanf("%d", &num);
fgets(name, sizeof(name), stdin);

If the user pressed 5 Enter X Enter, the program would set num to 5, but name would be set to a string with a single '\n', rather than 'X'. This is because scanf fails to remove '\n' produced by Enter from the buffer, so scanf finds it, and thinks that the user just entered an empty string.

Upvotes: 7

Related Questions