I am taking a training course on "C" and running into a problem. It's hard to explain so I'll post the code. This is training syntax, so don't ask me why it's done the way it is. When both of these segment blocks are run in a main(), the second block does not behave as if it exists alone in the main(). I have tried several IDE thinking it might be a bug.
/* First Segment Block */
int c;
printf("Type a letter: ");
c = getchar();
printf("You typed '%c'\n",c);
/* OR - outputs the same, to demonstrate putchar */
printf("You typed '");
putchar(c);
printf("'\n\n");
/* Second Segment Block */
int a,b,d;
printf("Type two letters: ");
a = getchar();
b = getchar();
d = getchar();
printf("You typed '");
putchar(a);
printf("' and '");
putchar(b);
printf("' and '");
putchar(d);
printf("'\n");
In the second segment block, I added a 3rd variable to test my theory. When you type the requested 2 letters, the first getchar() picks up a new line and the second getchar() picks up the first letter. The 3rd getchar() picks up the second letter. If you comment out the entire first segment block, then it behaves correctly, picking up the first letter by the first getchar() and the second letter by the second getchar(), displaying the output as expected.
Here is the output when both run together.
Type a letter: k
You typed (k)
You typed 'k'
Type two letters: lk
You typed '
' and 'l' and 'k'
RUN SUCCESSFUL (total time: 9s)
When they are run individually, the output is below.
First Segment Output.
Type a letter: k
You typed (k)
You typed 'k'
RUN SUCCESSFUL (total time: 5s)
Second Segment Output.
Type two letters: rf
You typed 'r' and 'f' and '
'
RUN SUCCESSFUL (total time: 5s)
The 3rd getchar() is a newline and that is expected.
Can anyone explain why when both segments are run in the same main(), the behavior is different from when run seperate?
Thank you in advance, Daniel N. (C language beginner)