在 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