Maxian Nicu
Maxian Nicu

Reputation: 2294

C skipping getch

I was surprised when i saw that in some cases C is skipping some inputs. In my case I'm using Ubuntu with Code::Blocks(xterm). For example, if i have following part of code :

scanf("%d",&someInt);
getch();

I can input a number,but pressing enter,it saves value for someInt and sends ENTER char automatically to getch(). I was expected for my program to wait to press any key after inputing number and pressing enter. But this not happen. I have found a solution to this, but this isn't a good one.

scanf("%d",&someInt);
getch();
getch();

Using two getch() it solves my problem. I'm entering number and I must press any key to continue. Why this happens ? How to solve it ?

Upvotes: 1

Views: 627

Answers (2)

tivn
tivn

Reputation: 1923

You can include newline char in the scanf format:

scanf("%d\n", &someInt);
getch();

Upvotes: 0

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

getch() reads a character and in your case it is reading a \n because after reading someint a newline character is left in the buffer.

Upvotes: 2

Related Questions