ccompiler-errorsoutputborland-c

Having trouble with C program output


As far as I know regardless of any other issues the program below should print out the title and menu options, and then prompt for user input.

However, it does absolutely nothing and when I stop the execution it prints out the menu etc and then, as it hasn't asked for the user inputted option it repeatedly prints the "This is not a valid option" line.

*EDIT: I have completely removed the loops. All I have in the program is print the title, print the menu, ask for user input, and I still get nothing to the console until after I terminate. Is there something wrong with my asking for input?

EDIT2: It's definitely the scanf as without it everything works. I ran the code with an added function to print out the value stored in option and it told me -1 when I hadn't previously set it to 0 before asking the user to input. The program seems to be automatically assigning option instead of bothering to ask the user what they want.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main ()
{
    /*Print Title*/
    printf("Maths Quiz Game \n"); 
    printf("\n");

    int i;
    int rightCount = 0; //count of right answers
    int wrongCount = 0; //count of wrong answers
    int questions = 0; //user input for number of questions
    int exit = 0; //store exit option
    int option = 0; //menu option

    while(exit == 0) //while loop that keeps program running until exit is chosen
    {
        /*Menu Options*/
        printf("Please choose an option from the menu below. Enter the number of your choice. \n");
        printf(" 1. Choose number of questions for this round. (Max = 5) \n");
        printf(" 2. Start Quiz \n");
        printf(" 3. Display total of right and wrong answers. (Only availanle after quiz) \n");
        printf(" 4. Exit Game \n");

        scanf("%d", &option); //taking user menu option

        /*Error check for any input that is not a valid option. It continues until valid entry*/
        while((option != 1) || (option != 2) || (option != 3) || (option != 4))
        {
            printf("\n That is not a valid option. Please try again. \n");
            scanf("%d", &option);
        }

Solution

  • The problem was with the printf function in that it didn’t print out until after you had entered the following options, it didn’t ask until after the user had answered. A simple flush after the printf sorted this out.