why cout work after getch in C++??!! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

why cout work after getch in C++??!!

I want to show a message before an input : cout<<"Enter a char:"; ch = getche(); but when running program it does not show the message and getche() works and after that the message is showed !!!

20th May 2022, 6:19 AM
Akbar Khalilzadeh
Akbar Khalilzadeh - avatar
7 Answers
+ 2
Yes, I thought so. This is beyond my expertise, though. This usually rrquires additional libraries (that probably interface via C), non-standard functions, or tapping into the keyboard interrupt. If it helps, you can try syncing C++ streams with C stdio using ios::sync_with_stdio(). Maybe this will already do the trick. But getche() is non-standard, so, maybe it won't. Maybe someone else is able to give an authoritative answer.
20th May 2022, 7:58 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Thou shalt not mix C++ streams and C stdio. The weirdest things can happen if those two are unsynchronized.
20th May 2022, 6:33 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
The whole problem is that, i want to do is : 1- show a message 2- enter ONLY one char 3- do something immediately after entering the char
20th May 2022, 6:51 AM
Akbar Khalilzadeh
Akbar Khalilzadeh - avatar
+ 1
for example when i pressed "a" it print "apple" but not with ENTER key only when i pressed "a" it goes and prints apple
20th May 2022, 7:08 AM
Akbar Khalilzadeh
Akbar Khalilzadeh - avatar
+ 1
@Ani Jona very thanks for your guide adding endl solved my problem cout<<"Enter a char:"<<endl; ch = getche();
20th May 2022, 9:02 AM
Akbar Khalilzadeh
Akbar Khalilzadeh - avatar
+ 1
endl will flush the output stream. Happy to hear it is enough to sync :)
20th May 2022, 10:58 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
0
I am a little concerned about the "do something immediately". You mean that you want the program to react to a keypress event?
20th May 2022, 6:58 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar