Possible Duplicate:
Program doesn’t wait for user input with scanf(“%c”,&yn);
I've just started programming in C, and something strange (which I didn't encounter in C++) is popping up.
In my header file, I declare a variable (see onemoretime
in code for .h
file), whose value is later set using user input through scanf()
. For some reason, the conditionals which use the variable wouldn't work properly, either returning an infinitely repeating result, or just not doing anything. I set some breakpoints, and found that the first time onemoretime
is called in the main()
function, the value of onemoretime
is, for some reason, set to \n
.
This isn't a value scanf()
is supposed to recognize, but the input is treated like a new line (obviously). When I enter y
, which should trigger the else if
conditional and loop back to the beginning of main()
, Xcode's debugger simply says, error: 'y' is not a valid command.
Here's my .h
file:
#ifndef C1_Header_h
#define C1_Header_h
float num1, num2;
char op, onemoretime;
#endif
... And here's the relevant code from the .c
file:
#include <stdio.h>
#include <math.h>
#include "Header.h"
int main(int argc, const char * argv[])
{
printf("Enter a two-number calculation below:\n");
while (1)
{
scanf("%f%c%f", &num1, &op, &num2);
// addition
if (op == '+')
{
printf("%f\n", num1+num2);
printf("\nDone. Would you like to solve another math problem (y/n)?\n");
scanf("%c", &onemoretime);
while (1)
{
if (onemoretime == 'n')
{
printf("Ok. Terminating program.");
return 0;
}
else if (onemoretime == 'y')
{
// loop back to start main function
}
}
}
}
// rest of code, irrelevant here
}
If it's a factor at all, hovering over the onemoretime
variable in Xcode (showing its basic properties), every instance of the variable after the initial declaration in the header file shows the value to be \n
.
What am I doing wrong? How can the value of onemoretime
be set by the user, rather than being set by the program before the user can get to it?