I wan to read two char so I do the following code:
main() {
char a,b;
printf("\nEnter the first char.. ");
a=getchar();
printf("\nEnter the second char.. ");
b=getchar();
b=getchar(); //<--I've to add this sentence because the previously doesn't work
printf("\nFirst char --> %c",a);
printf("\nSecond char --> %c",b);
}
The code should not work but it does. The output is the correct:
First char –> z
Second char –> z (‘z’ or the char there I wan to)
If I remove the second getchar() then the output is:
First char –> z
Second char –> (Here there is no char)
How can I remove the second getchar() without get any error?
Because fflush(stdin) before getchar() doesn’t work.
As indicated by the other answers, the problem was caused by the carriage return.
There are many ways solve this, some more complex than others. Therefore I will indicate the simplest method I’ve found:
As the GNU website indicate the most appropriate function for this is
getc(stream)and I quote:I put it into practice but it still have the CR problem, so I printed the result of this function and notice that it return 10 when CR.
After this I tried to get functionality and clarity for the code. Doing everything possible for this, now my code is the following:
And the nice output:
I’ve learned that all the programs need they own solution, different than the others, and that is the reason (I think) for that are so many functions. What I can say is “Always have to adapt the program. Maybe this sentence works for me but is not guaranteed that gonna work for other codes.”
Thanks to all the guys that helped me!