Search code examples
cfgets

fgets printing two lines before input


So I am trying to write a program that will let me read a user input for data on an MP3 file using a doubly linked list data structure. I got most of the methods and functions to work, but when I am prompting the user to put in input it prints out two lines before the user can input for the first line. So for example

int main()
{
    int user_input = 0;

    while(!(user_input >= 4))
    {
            struct MP3_data_node* MP3_data;
            MP3_data = (struct MP3_data_node*)malloc(sizeof(struct MP3_data_node));

            printf("\nPlease select a number for one of the following instructions:\n");
            printf("0: add to list\n1: delete from list\n2: print the list from beginning to end\n3: print the list from end to beginning\n4: exit\n");

            scanf("%d", &user_input);

            if(user_input == 0)
            {
                    printf("Please provide the artist:");
                    fgets(MP3_data->artist,50,stdin);
                    printf("Please provide the album:");
                    fgets(MP3_data->artist,50,stdin);
                    printf("Please provide the song title:");
                    fgets(MP3_data->artist,50,stdin);
                    printf("Please provide the year the song was released: ");
                    scanf("%d", &MP3_data->yearReleased);
                    printf("Please provide the length of the song in seconds: ");
                    scanf("%d", &MP3_data->runTime);

                    addToList(MP3_data);
            }
...

So it prints out "Please provide the artist:Please provide the album:" and then let's me put the input in, so my question is how do I make it so that it prints: Please provide the artist: (user input) Please provide the album: (user input) etc.


Solution

  • You're doing the right thing (fgets) int the first few prompts, then you switch to scanf which is the source of your problem. Use fgets (and strtol) instead of scanf and you will be fine. (And, the first scanf which causes the problem described in your question.)

    The problem is that scanf only reads the digit part of whatever you enter. That means if you type 12Enter, then the scanf reads the 1 and 2 but leaves the Enter in the input buffer for the next call to fgets or scanf. On the other hand, fgets reads everything you type including the Enter, avoiding this problem.