C++ 检测Ctrl+;d如果使用getchar()输入缓冲区不是空的
我正在使用C++ 检测Ctrl+;d如果使用getchar()输入缓冲区不是空的,c++,console,getchar,C++,Console,Getchar,我正在使用getchar()为缓冲输入编写一个类似shell的解释器 如果按下Enter,解释器应处理缓冲区,然后提示输入新行 如果按下Ctrl+d,解释器应处理缓冲区,然后退出 下面的代码可以运行,但不能完全满足第二个要求 #include <iostream> using namespace std; void shell() { for (int input;;) { // prompt at beginning of line
getchar()
为缓冲输入编写一个类似shell的解释器
- 如果按下
,解释器应处理缓冲区,然后提示输入新行Enter
- 如果按下
,解释器应处理缓冲区,然后退出Ctrl+d
#include <iostream>
using namespace std;
void shell() {
for (int input;;) {
// prompt at beginning of line
std::cout << ">>> ";
while ((input = getchar()) != '\n') {
// still in current line
if (input == EOF) {
// ctrl+d pressed at beginning of line
return;
}
std::cout << "[" << (char)input << "]";
}
// reached end of line
}
}
int main() {
cout << "before shell" << endl;
shell();
cout << "shell has exited" << endl;
return 0;
}
#包括
使用名称空间std;
空壳(){
对于(int输入;;){
//行首提示
std::cout对于一个普通的行,在末尾有一个'\n'
。而对于在Unix land shell中用Ctrl+D按下的行,情况并非如此。例如
#include <stdio.h>
#include <unistd.h> // read
void shell()
{
char line[256];
for( bool finished = false; not finished; )
{
printf( ">>> " );
//fgets( line, sizeof( line ), stdin );
fflush( stdout );
const int n_bytes = read( 0, line, sizeof( line ) - 1 );
line[n_bytes] = '\0';
char const* p = line;
finished = true;
while( char const input = *p++ )
{
if( input == '\n' )
{
finished = false;
break;
}
printf( "[%c]", input );
}
printf( "\n" );
}
}
auto main()
-> int
{
printf( "before shell\n" );
shell();
printf( "shell has exited\n" );
}
#包括
#包含//读取
空壳()
{
字符行[256];
for(bool finished=false;not finished;)
{
printf(“>>>”);
//fgets(生产线、尺寸(生产线)、标准DIN);
fflush(stdout);
const int n_bytes=read(0,行,sizeof(行)-1);
行[n_字节]='\0';
char const*p=行;
完成=正确;
while(char const input=*p++)
{
如果(输入=='\n')
{
完成=错误;
打破
}
printf(“[%c]”,输入);
}
printf(“\n”);
}
}
自动主机()
->int
{
printf(“在shell之前”);
外壳();
printf(“shell已退出\n”);
}
留给您解决以下问题:
- 手柄EOF(空线按下)
重写C++的IOFROTS,不是C<代码>文件*/COD> I/O.
- 对于按Ctrl+D键的输入行,控制台输出中缺少换行符
注1:read
通常也适用于Windows编译器。但是
注2:按Ctrl+D键推送当前行是一种Unix land约定。如果您希望您的程序无论如何运行或在什么系统上都显示这种行为,则必须使用一些可移植的低级字符输入库,如ncurses。对于普通行,末尾有\n
。对于按Ctrl+D键推送的行,情况并非如此@Cheers:如何确定除\n
以外的字符是否在行尾,或者行尾尚未结束?使用stdio无法完成此操作,您需要使用低级输入函数。说明如何在不等待“回车”的情况下读取字符有跨平台解决方案吗?我的错,我确实按了两次Ctrl D。嗯!@TaylorNichols好的,通过使用Unix landread
OS API函数而不是Cfgets
修复了它。