Int function returns null without waiting for user input for scanf

I am trying to write a simple function that prompts the user for a character, then echoes back, "The character you entered was: " character.

Then the user should enter 'Q' to quit, will be prompted by the question "are you sure you want to quit (y/n)?" and inputting a 'Y' will cause the program to quit.

However in running the 'int endProgramFunction( void )' the program returns null before waiting for the user input "Y" or "N", and then returning 1 or 0, as it should.


Here is the source code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
******************************
#include <string.h>
#include <stdio.h>


int endProgramQuestion( void )    //called when a user enters 'Q', confirms Quit
{
        char d;
        printf("%s You have chosen to end this program\n Are you sure you want to continue (Y/N)? \n" );
        d = getchar();

        if (d == 'Y')              //user enters 'Y' to Quit
        {
                return 1;
        }

        else
        {
                return 0;
        }
}

main()
{
   int prog_over; //int to see if the while loop should end.
   prog_over = 0;

   printf("Enter a Character to have it Echoed back to you. \n Enter 'Q' to quit.\n");


   while (  prog_over == 0 )
   {
        char c;
        c = getchar();

        if(c != '\n') // so that 'enter' doesn't count enter as a character
        {
            printf("The Character you entered was: \n");
            printf("%c \n" , c );
        }

        if(c == 'Q' ) //if the user enters 'Q' to quit, goes to confirm
        {
                if(endProgramQuestion() == 1)
                {
                        prog_over = 1 ;
                }
        }
   }
}
*********************

I can get the program to work by setting a "return 1;" statement at the beginning of "endProgramQuestion()", but then it no longer checks to see if the user really wants to quit.

I am running on the latest Cygwin, using GCC to compile, OS: windows XP.

Thanks all in advance for your help :).
Last edited on
[code] "Please use code tags" [/code]
I guess that you pressed 'enter' after 'Q'.

You shouldn't lie in the formant string.
Ah Thanks that let me fix it by adding another getchar() to account for the \n character.
Much appreciated :)
Topic archived. No new replies allowed.