system("pause"); doing weird things ???

please help me.
I have such testing code insert in one of my sub:
I need to have a output on screen: "(i,j)=...:ratio4=...." and have a pause till I hit key.
But when I run, message 'please press any key to continue ...' appears first !!!!
and when I hit a key, other message appears including '(i,j)=...:ratio4=....'
did I missed anything ? please help

1
2
3
4
5
6
7
8
double func_selfpre(int i) 
{ 
   if (i==5 && j==133)
   { cout << "(i,j) = ("  << i <<j<<"):ratio4=  "<<ratio4<<'\n';
     system("pause"); } 
	 
   return (0);
}




That's how system("pause") works. It calls the command "pause" in the windows console.

Try using something else like cin.get().

More info:
http://cplusplus.com/forum/beginner/1988/
1
2
3
4
5
6
7
8
9
double func_selfpre(int i) 
{ 
   if ((i==5) && (j==133))
    cout << "(i,j) = ("  << i <<j<<"):ratio4=  "<<ratio4<<endl;
 
 
   system("pause");	 
   return 0;
}
Last edited on
I'd thoroughly advise you not to use system("pause") at all, and instead to use cin.get().

However, if you have to use it and don't want the message to be displayed, you can use system("pause>nul").

That being said, don't use it.
many thanks for above helps.

maybe I didn't mention clearly. I don't mind message 'please press key ...'

but I need output first and then pause.
my code did opposite !!!

I will try cin.get().
be back...


cin.get() really works!!!

thanks guys so much.
To explain why: cout is buffered by default, which means the output is only shown when the cout buffer is flushed. That happens on buffer overflow, on any input from cin, on any output to cerr, on program termination, on a call to std::flush, and on a call to std::endl, but *not* on system() call.

in your program, output was posted to cout, but not flushed (so it was not shown) when you called system("pause")

in the cin.get() solution, the call to cin.get() flushes cout and causes the output to appear

in the endl solution, the call to std::endl() does the same
Last edited on
Topic archived. No new replies allowed.