C++ code doubt

Sep 30, 2012 at 6:17pm
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;
} 
Oct 1, 2012 at 12:48pm
Line B is not executed first, line 9 is executed first
Oct 1, 2012 at 4:32pm
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?
Oct 1, 2012 at 4:46pm
Did you try cout.flush(); after line 17?
Oct 1, 2012 at 4:48pm
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
Oct 2, 2012 at 8:40am
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.
Oct 2, 2012 at 8:41am
Did you try cout.flush(); after line 17?


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

Wazzak
Oct 2, 2012 at 9:01am
Yes i have tried fflush(stdin);

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