0

In a C program inside int main() function I have a while loop which asks the user for a char as input and call a method after getting the input. The method which is called after getting the input uses a switch to print or call other function. The problem is that after the first run of the while loop and getting input from user and after that the case which is matched finished, the while loop runs once automatically with out waiting for the user to enter anything. This behavior is strange for me as a newbie in C. Therefore, I want to know how should I handle this situation to prevent the automatic run of while loop and force the program to wait for user to enter anything to the terminal? Bellow is my code:

void switchFuncs(struct driver *allDrivers, char operation)
{
    int driverCounter = 0;
    char srchDriver[20];
    int birthYear = 0;
    double kolo = 0.00;
    int pKolo = 0;

    convert_file_data_to_struct(allDrivers, &driverCounter);

    switch (operation)
    {
        case 's':
            printf("Case S is called!!!!\n");
            break;
     
        case 'c':
            printf("Case C is called!!!!\n");
            break;
        case 'n':
            newdriver(allDrivers, driverCounter);
            break;
        case 'x':
            exit(0);
            break;
        default:
            printf("What you typed is not a valid operation!!! \n");
            break;
    }

}

int main()
{
    char operation = 't';
    struct driver *allDrivers;
    int flag = 1;

    while (flag == 1) {
        char operation;
        printf("Select the operation you want to do from the following list: \n\n");
        printf("For Summary Type s \nFor Change Name type c \nFor New Name type n \n");
        printf("To Exist From Program type x \n");
        scanf("%c", &operation);
        if( operation == 'x' || operation == 'X') {
            flag = 0;
        }
        allDrivers = (struct driver*) malloc(1500 * sizeof(struct driver));
        switchFuncs( allDrivers, operation );
        free(allDrivers);
    } 
    return 0;
} 

Bellow is a sample result after just one time run of the program:

Select the operation you want to do from the following list: 

For Summary Type s 
For Change Name type c 
For New Name type n 
To Exist From Program type x 
s
Case S is called!!!!
Select the operation you want to do from the following list: 

For Summary Type s 
For Change Name type c 
For New Name type n 
To Exist From Program type x 
What you typed is not a valid operation!!! 
Select the operation you want to do from the following list: 

For Summary Type s 
For Change Name type c 
For New Name type n 
To Exist From Program type x 
Ibrahim Rahimi
  • 519
  • 8
  • 31

1 Answers1

1

Put a space before "%c", as this:

scanf(" %c", &operation);
       ^
// Space between " and %c

See the explanation here: https://stackoverflow.com/a/17079227/1755482

Milo
  • 2,062
  • 16
  • 38