Need replace enter key c++

I am trying to find a way to replace pressing enter key in c++.
below is c code.
can someone help me?
after press enter key detected, user needs to provide some inputs to proceed further, which means that I need to allow the program in C++ to key in another inputs if an <enter key> is pressed

1
2
3
4
5
6
void PressEnter ()
{
    printf("Press Enter to quit");
    fflush(stdin);
    getchar();
}
Last edited on
fflush(stdin); engenders undefined behaviour.

For input streams (and for update streams on which the last operation was input), the behavior is undefined.
https://en.cppreference.com/w/c/io/fflush


See if this works for you: https://www.cplusplus.com/forum/general/170262/#msg849987
Actually once enter key is pressed, user needs to add some additional inputs like the below.
how can this be done?

Usage: "<TCP Server Port> <TCP Server IP> <hostname> "
Last edited on
See if this works for you:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <limits>

void pause( const char* prompt = "press enter to continue..." )
{
    std::cin.clear() ;
    auto stmbuf = std::cin.rdbuf() ;
    const int nothing = std::char_traits<char>::eof() ;
    const std::streamsize everything_upto = std::numeric_limits<std::streamsize>::max() ;
    const char new_line = '\n' ;

    if( stmbuf->in_avail() || ( stmbuf->sungetc() != nothing && std::cin.get() != '\n' ) )
        std::cin.ignore( everything_upto, new_line ) ;

    std::cout << prompt ;
    std::cin.ignore( everything_upto, new_line ) ;
}

int main()
{
    // some or no user inputs
    pause() ;
    // accept additional user inputs
}
Unfortunately not with VS/Windows. Any existing chars in the input stream aren't removed before the prompt is displayed (which is what the if statement is attempting). So if existing input stream chars contain a '\n' char, then the .ignore() will return immediately.

What is needed is a cin.flush() function - but I don't know just using standard c++.

The issue is that even if there is cin data available, ->in_avail() returns 0 and ->sungetc() returns eof so the first .ignore() is not executed to remove existing input data before the prompt is displayed.

If your compiler supports conio.h (and VS does), then the 'old' way of flushing the input buffer could be used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void cinflush()
{
	std::cin.clear();

	for (; _kbhit(); _getch());
}

void pause(const char* prompt = "press enter to continue...")
{
	cinflush();

	std::cout << prompt;
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}


Note that _kbhit() and _getch() might just be kbhit() and getch() without the leading -
Topic archived. No new replies allowed.