0

I have written a program that is far too long to copy to this site. But what is needed will be pasted into the website.

Here is the switch statement:

    void enterName();

    int adminChoice;
    printf("\nEnter Numeric Choice: ");
    scanf("%d", &adminChoice);

    switch(adminChoice)
    {
        case(1):
        {
            enterName();
        }
    }

Here is the actual function:

void enterName()
{
    FILE *fp = fopen("/home/matthew/Desktop/BBE.txt", "w");

    if (fp == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }
    char comment[100];

    printf("Enter, String\n");

    fgets(comment, sizeof comment, stdin);
    fputs(comment,fp);
}

What happens is the program asks for user input of a string. But does not allow for time to put in a desired string. It just ends the program.

  • 2
    When you enter the value for `adminChoice`, remember that you end it with a newline (the `Enter` key). This key is added to the input buffer to be read from `stdin` the next you want to read something. Now think what happens when you call `fgets` when this newline is the first character in the `stdin` input buffer. – Some programmer dude Jan 22 '17 at 18:32

1 Answers1

2

The problem is that scanf() leaves a \n character which terminates the fgets() immediately without reading anything. fgets() would stop reading when it sees a newline character or EOF.

You could use a hacky approach and use a getchar(); right before fetgs() call. Better option is to use fgets() to read the adminChoice (and convert it to integer using sscanf() or strto* functions) as well so that you avoid scanf(). In any case, you always have to watch out for newline character when using fgets().

P.P
  • 117,907
  • 20
  • 175
  • 238