cin.get(); doesn't work, but system("pause"); does

So, my problem is that I would love to use cin.get(); instead of system("pause"); but it's not just working on application I just made. For previous it worked great.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
using namespace std;

int cipars;
cout << "How many do you want?";
cout << endl;
cin >> cipars;
cout << "You want: ";
cout << cipars;
cout << endl;

cin.get();
return 0;
}

Last edited on
You had a '\n' left in your cin's buffer when you called cin.get(), which got the new line and then moved on.

To clear the buffer, I vaguely recall that cin.sync(); would do it.

-Albatross
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
using namespace std;

int cipars;
cout << "How many do you want?";
cout << endl;
cin >> cipars;
cout << "You want: ";
cout << cipars;
cout << endl;

cin.sync();
return 0;
}


Hmm... that did not fix it.
Last edited on
You'll still need the cin.get() (or cin.ignore()). cin.sync() clears the buffer, cin.get()/ignore() tries to get something from the buffer, but because it's empty it will pause the console and prompt the user to fill it up.

-Albatross
Seems worked fine with

1
2
cin.get();
cin.ignore();


Thanks Albatross!
I'd prefer a builtin std::pause(); function to those input stream hacks.
Or system("PAUSE"); for that matter.
For professional programming (at least), the system() function can't always be trusted. For simply testing a program, maybe, but I personally still wouldn't use it.

I would also prefer a std::pause() function, but seeing as there isn't one we'll make do with what we have.

-Albatross
closed account (zb0S216C)
try this:

1
2
3
4
void Pause( void )
{
    std::cin.ignore( std::numeric_limits< std::streamsize >::max( ), '\n' );
}

If you've included <Windows.h>, you'll have to modify the above code:

1
2
3
4
void Pause( void )
{
    std::cin.ignore( ( std::numeric_limits< std::streamsize >::max )( ), '\n' );
}

Wazzak
Topic archived. No new replies allowed.