在 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