Search code examples
cscanffgetsgets

How to solve this gets() function problem?


In my program if I use scanf(), the program works fine. But as it is obvious, scanf() stops reading the input if it encounters a whitespace. So, instead I used gets(). But the problem is I have to use gets(name[i]); twice. If I use it only once, it skips the 'Subject Name' input & jumps to 'Grade' input.

Can you tell me where the problem lies? Here is the code, I removed almost all irrelevant parts.

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void selection1();

int main()
{
    int op;

    printf("\n\t\t\t\t\t\t\t\tCHOOSE A NUMBER FROM 0 to 4: ");
    scanf("%d", &op);
    switch(op)
    {
    case 0:
        exit(0);
        break;
    case 1:
        selection1();
        break;
    case 2:
        //selection2();
        break;
    case 3:
        //selection3();
        break;
    case 4:
        //selection4();
        break;
    default:
        printf("\t\t\t\t\t\t\t\tInvalid Selection!!!\n");
        break;
    }
    return 0;
}

void selection1()
{
    char name[20][50], grade[20][5];
    double credit[20][2];
    int i=0;

    for(;;)
    {
        printf("\t\t\t\t\t\t\t\tEnter Subject Name: ");
        gets(name[i]);
        //gets(name[i]);
        printf("\t\t\t\t\t\t\t\tEnter Grade: ");
        scanf("%s", &grade[i]);
        printf("\t\t\t\t\t\t\t\tEnter The Course Credits: ");
        scanf("%lf", &credit[i]);
    }
}

Solution

  • So, I found using scanf(" %[^\n]%*c", &name[i]); instead of gets(name[i]); solve the problem. Thanks to everyone who commented. Your comments helped me to reach this answer :)