在 C++ 中從標準輸入讀取字元,而不必等待換行符


不存在可移植的解決方案來執行此操作。在 Windows 上,可以從 conio(控制檯 I/O) 庫中使用 getch() 函式來獲取按下的字元。

示例

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

這將輸出你輸入到終端中的任何字元。請注意,這僅適用於 Windows,因為 conio 庫僅存在於 Windows 上。在 UNIX 上,可以透過進入系統原始模式來實現此目的。 

示例

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

更新於: 2020 年 2 月 12 日

3K+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.