-
Scanf problem
I'm having a problem with my program skipping over the 2nd scanf function. I am new to programming and am not sure why this is.
when I run this I do not get prompted for a 2nd input, it just skips right over it.
Code:
int
main(void)
{
int success,m,n,ans,input;
char op;
printf("Enter a simple arithmetic expression.\n");
success = scanf("%d%c%d\n",&m,&op,&n);
switch(op)
{
case'+':
ans = m + n;
printf("What is the answer to %d%c%d?\n",m,op,n);
scanf(" %d\n" , &input);
if(ans == input)
{
printf("correct!\n");
}
else
{
printf("No, the correct answer is %d\n",ans);
}
break;
case'-':
ans = m - n;
break;
case'*':
ans = m * n;
break;
case'/':
ans = m / n;
break;
case'%'
ans = m % n;
break;
}
printf("%d\n",success);
return 0;
-
Very common complaint. When you hit enter, the input stream gets a newline put into it. That newline char is NOT included in your variable, but it's left in the buffer. When the next scanf() is reached, the buffer is read. If a char will foul things up at that time, then it will be "skipped".
You can fix it by adding a blank space before the first % in the second scanf(), or by putting a getchar() line of code, after the first scanf(). that will fix the problem.
Since you've already tried the first method, I strongly suggest the latter, ( the getchar() ), and put it after each of the two scanf()'s, just to be thorough.
-
Thank you very much! The getchar()worked perfectly.