repeat a program without pressing ENTER

this code forces users to press enter

i dont want them to press enter
i just want them to press a number to repeat or 0 to exit

its like a keyboard
you dont have to press enter to type in every letter
1
2
3
4
5
6
7
8
9
10
  int repeat;
	do{
	
	//code
	
	cout << endl;
	cout << "Enter any number to repeat, 0 to exit: ";
	cin >> repeat;
	}while(repeat != 0);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
   int n{};
   do
   {
       std::cout << "Enter number \n";
       std::cin >> n;
       if(n != 0)
       {
            std::cout << "Number is " << n << "\n";
       }

   } while (n != 0);
}
i have to press enter
You need to put your terminal in raw mode.
There is no standard way to do that. Under a Unix-like system, something like this may work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#   include <termios.h>
#   include <unistd.h>
#   include <cstdlib>
#   include <errno.h>

static termios old_tios;

bool raw_stdin() noexcept {
  /* Copy defaults from the old state. */
  termios newtermios = old_tios;

  newtermios.c_lflag &= ~(IEXTEN | ICANON);
  newtermios.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  newtermios.c_oflag &= ~OPOST; /* No post-processing. */
  newtermios.c_cflag &= ~(CSIZE | PARENB);
  /* One byte at a time */
  newtermios.c_cc[VMIN]  = 1; newtermios.c_cc[VTIME] = 0;
  return (tcsetattr(STDIN_FILENO, TCSAFLUSH, &newtermios) == 0);
}

bool cooked_stdin() noexcept {
  return tcsetattr(STDIN_FILENO, TCSAFLUSH, &old_tios) == 0;
}

This is just ripped from a short program of mine... call raw_stdin() to try to put the terminal in raw-mode; you can read individual characters like this.
1
2
3
4
char c {};
if (sizeof c != read(STDIN_FILENO, &c, sizeof c)) 
  perror("read(): ");
}

You need to make sure that the old_tios object gets initialized:
1
2
3
  if(tcgetattr(STDIN_FILENO, &old_tios) != 0) {
    std::perror("tcgetattr()");
  }

Because this affects the terminal, you must (should) ensure that you put it back in cooked mode before you quit.

For Windows systems, follow this post:
http://www.cplusplus.com/forum/beginner/3329/
Last edited on
Topic archived. No new replies allowed.