在 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