C++ code doubt

Why line B is getting executed before line A in following cpp program ?


As after running,the line A displays after you press EnteR.
but getchar comes after line A.Why enter is required first???
(I am using visual c++)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{

char ch;
cout<<"Enter a character: ";
cin>>ch;


for(int i=65;i<=122;i++)
{
if(ch==i)
{
cout<<"The ASCII value of "<<ch<<"is : "<<i; [line A]
cout<<"Press Enter to Exit";
getchar();                                   [line B]

exit(0);
}
}


return 0;
} 
Line B is not executed first, line 9 is executed first
actually the problem is, on running the code :

A character is asked .(user types character and presses enter)

Then the ASCII value gets printed after you press 'Enter key'.

This means line 19 is causing me to press enter and then line 17 is displaying ASCII value.
why so?
Did you try cout.flush(); after line 17?
This means line 19 is causing me to press enter and then line 17 is displaying ASCII value.


no, you're totally misunderstood. the one that make you press "enter" is this:

cin>>ch;

CMIIW
1
2
3
no, you're totally misunderstood. the one that make you press "enter" is this:

cin>>ch; 


I know i have to press enter after typing a character due to
cin>>ch;.

But after that i have to press an additional Enter and that is my doubt.
Did you try cout.flush(); after line 17?


Yes i have tried fflush(stdin);
The problem still persists.
closed account (zb0S216C)
If you don't want to press enter a second time, don't call "getchar( )".

Wazzak
Yes i have tried fflush(stdin);

Was that a simple typo? I was referring to stdout.
Topic archived. No new replies allowed.