Read a character from standard input without waiting for a newline in C++

C++Server Side ProgrammingProgramming

A portable solution doesn't exist for doing this. On windows, you can use the getch() function from the conio(Console I/O) library to get characters pressed.

example

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
    char c;
    while(1){ // infinite loop
        c = getch();
        cout << c;
    }
}

This will output whatever character you input to the terminal. Note that this will only work on windows as the conio library exists only on windows. On UNIX, you can achieve this by entering in system raw mode. 

example

#include<iostream>
#include<stdio.h>
int main() {
    char c;
   // Set the terminal to raw mode
    system("stty raw");
    while(1) {
        c = getchar();
        // terminate when "." is pressed
        if(c == '.') {
            system("stty cooked");
            exit(0);
        }  
        std::cout << c << " was pressed."<< std::endl;
    }
}
raja
Published on 28-Feb-2018 15:44:49
Advertisements