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


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;
    }
}

Updated on: 12-Feb-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements