Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

อ่านตัวอักษรจาก standard input โดยไม่รอ newline ใน C++


ไม่มีวิธี portable (รองรับทุก OS) สำหรับอ่านตัวอักษรทีละตัวโดยไม่รอ Enter

Windows: ใช้ conio.h (getch)

#include <iostream>
#include <conio.h>
using namespace std;

int main() {
    char c;
    while (1) {
        c = getch();      // อ่านทันที ไม่รอ Enter
        cout << c;
    }
}

ทำงานได้เฉพาะ Windows เพราะ conio.h มีเฉพาะ Windows

UNIX/Linux: ใช้ raw mode

#include <iostream>
#include <stdio.h>
#include <cstdlib>

int main() {
    char c;
    system("stty raw");   // ตั้ง terminal เป็น raw mode
    while (1) {
        c = getchar();
        if (c == '.') {   // กด '.' เพื่อออก
            system("stty cooked");
            exit(0);
        }
        cout << c << " was pressed." << endl;
    }
}

ใช้คำสั่ง stty raw ปิดการ buffer input แบบบรรทัด ทำให้อ่านตัวอักษรทันที