Give this a read. There can be problems with stray '\n' (newline) characters in the buffer. The code snippet there shows how to flush them out (and even offers the use of getchar as a more effective method in this case.
jonsca
Quantitative Phrenologist
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
Scanf isn't clearing the input buffer of the new line character..
i.e. When you enter an operator you enter the operator character plus you hit the return key...So two characters are placed in the input buffer, the one you want plus the newline character and scanf only picks up the operator character leaving the newline in the buffer.
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
#include <stdio.h>
#include <stdlib.h>
int main(){
char option, factor;
printf("Choose your operator: \"+\" ; \"-\" ; \"*\" ; \"/\" \n>\t");
scanf(" %c", &option);
printf("You chose : %c \nChoose your factor:\n>\t", option);
scanf("%d", &factor);
printf("You chose : %i\n",factor);
printf(" %c", option);
if(option=='+'){
printf("It's WORKING!");
system("pause");
}
return 0;
}
It looks like the problem would be that factor is of type char , but when you do the scanf(...) , you tell to input aninteger (i.e. "%d") instead of char . So, scanf() happily accepts anything that fits into an int , and because an int consumes more memory than a char , you will end up overwriting stack memory - and that changes the value of option .
You might add; printf("option is now [%c]", option); there, so that you see that the value has changed.
So you might remedy this by ..
int main(){
char option;
// 'factor' changed to int instead of char ...
int factor;
// .. and the rest of the code as is ...
I hope that made some sense. At any rate, you don't want to use mismatched/erroneousformat strings with any of the scanf/printf -family functions.
PS. hint: GCC is quite good at pointing out mismatched format strings.
mitrmkar
Posting Virtuoso
1,809 posts since Nov 2007
Reputation Points: 1,105
Solved Threads: 395
WaltP
Posting Sage w/ dash of thyme
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
On the other hand if i remove the do{ and }while(getnumber[o]!=' '); , the program works fine! It's just that I need this do loop there.
This is another one of those "what the heck" problems. If you remove the do-while and the code works fine, then you don'tneed the do-while .
Kinda like if you know how to get to your friend's house, you really don't need the GPS.
WaltP
Posting Sage w/ dash of thyme
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
Please post up your most recent code. I know you've made some changes, and I'm late joining this thread.
Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185