在 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;
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP