press enter to continue

Back, again ^^;
So basically, title. How do I make it that there is like a 'break' in the text. I'm aware of the following:
 
  cin.ignore();

and my problem with it is that it only sometimes works. I'm confused, I tested it out on atom.io and repl.it and had the same issue, is it just me? Is there something I'm doing wrong?

Is there a function alternative to this?
1
2
3
4
5
6
7
void enter_to_exit( )
{
    cout << "Press enter to exit...";
    if( !cin ) cin.clear( );
    cin.ignore( numeric_limits<streamsize>::max( ), '\n' );
    cin.get( );
}
@integralfx

Your code will not work everytime. If cin was not called by the overloaded operator >> (or another way), then this function causes the user to have to press the enter key twice.

This is because you have cin.ignore() and cin.get(). You should not use cin.ignore() when it was not used. Which I do not know of a way to check.
Last edited on

Your code will not work everytime. If cin was not called by the overloaded operator >> (or another way), then this function causes the user to have to press the enter key twice.

This is because you have cin.ignore() and cin.get(). You should not use cin.ignore() when it was not used. Which I do not know of a way to check.


I think I fixed it now.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void enter_to_exit( )
{
    cout << "Press enter to exit...";
    
    if( !cin ) cin.clear( );
    
    if( cin.peek( ) == '\n' ) {
        cin.get( ); 
        return;
    }
    
    cin.ignore( numeric_limits<streamsize>::max( ), '\n' );
    cin.get( );
}
Last edited on
integralfx wrote:
I think I fixed it now.

Still no. If the cin is used to read input into something, then the function doesn't pause.

Also, since your function has to have the <limits> library included, I don't think it is too convenient.
Last edited on

Still no. If the cin is used to read input into something, then the function doesn't pause.

Also, since your function has to have the <limits> library included, I don't think it is too convenient.


Formatted input: http://cpp.sh/6bea
Unformatted input: http://cpp.sh/43s5n

Works fine for both, for me.
This should work for most cases. Also please be careful when using cin.ignore(), since it may pause the program unexpectedly if used incorrectly.

cin.ignore(1000, '\n');

No one rarely goes that far to stock more than 1000 characters per input.
Last edited on
This should work for most cases. Also please be careful when using cin.ignore(), since it may pause the program unexpectedly if used incorrectly.


Thanks for providing an answer that was worse than my first implementation.
What if cin isn't good() ? It prematurely terminates.
What if the formatted input is used? It prematurely terminates.
cin.ignore() is often used with cin.clear() to handle stream errors.
However, cin.ignore() can be also used to remove trailing newline characters before using std::cin.getline().
Topic archived. No new replies allowed.