| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Why need two cin.get() ???
Hello everyone,
I write below programming exercise but, why i need to write two time cin.get () at the end in order to "hold" the screen??? If i just wrote one cin.get (), I found the progamme automatically close the screen after run the programme. I am using DEV++, will it be a reason? Thank you. // Programme to read and print the absolute value // #include <iostream> using namespace std; int main () { int value; cout << " Please enter a integer : "; cin >> value; if( value < 0 ) value = -value; cout << " The absolute value of the integer is :" << value <<endl; cin.get(); cin.get(); return 0; } |
|
#2
|
||||
|
||||
|
This is because of a keyboard buffer error. When you press <Enter>, all the keys you just entered get flushed through to the program, but the newline itself rarely does, thus the next time you request input there is only a single newline in the buffer so it automatically reads that in and, since it's a newline, terminates the stream right there.
Thus, your first cin.get() is just reading in the leftover newline from your first cin>>, and the second cin.get() is actually pausing the program.
__________________
Officially a member of the Itsacon fan club. Beer blasts are every friday at Viper_SB's house. I bring the chips. ![]() |
|
#3
|
|||
|
|||
|
Thanks B-con,
So, what should i suppose to do in order to de-bug it?? Thank you very much. |
|
#4
|
||||
|
||||
|
To fix the problem of using two cin.get()'s, I personally use the line "fseek(stdin,0L,SET_END)" before every string (or individual character) I read in, that will clear the buffer of any residue from previous inputs.
ie: Code:
fseek(stdin,0L,SET_END); cin>> str; . . . fseek(stdin,0L,SET_END); cin.get(); |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Why need two cin.get() ??? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|