将键盘快捷方式添加到C中的控制台应用程序

我写了一个程序,让用户输入单词,然后将它们保存到char数组,直到用户输入“* end”。当用户按下Ctr + Z而不是输入“* end”时,如何让程序停止?

这是代码

char text[1000][100]; char end[100] = "*end"; int count =-1; do { count++; scanf("%s",&text[count]); }while(strcmp(text[count],end)==1); 

这是scanf()man页说的返回值(不是参数值)

 RETURN VALUE On success, these functions return the number of input items success‐ fully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure. The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set to indicate the error. 

这归结为:

始终检查系统function返回的错误情况。

建议改变这个:`

 scanf("%s",&text[count]); 

至:

始终使用比输入缓冲区长度小一个的MAX CHARACTERS修饰符,以避免缓冲区溢出。 这种缓冲区溢出是未定义的行为,可能导致seg故障事件。

 int retScanf = scanf( "%99s", &text[count] ); switch( retScanf ) { case 1: // normal return // handle string input // this is where to check for 'end' break; case EOF: // ctrl-z return // user entered -z break; case 0: // invalid input return // user entered only 'white space' (space, tab, newline) break; default: // should always provide for unexpected 'switch case' // display error message here break; } // end switch 

它可能是特定于操作系统的 。 C11(或C ++ 14)标准不了解终端 (或终端仿真器 )或键盘,只关于标准输出 ,标准输入等….

在Linux上,阅读关于tty demystified , termios(3)并考虑使用一些库,如ncurses或readline 。

顺便说一句,你最好使用C 动态内存分配而不是使用数组数组,你应该检查scanf(3)的结果计数。 看看strdup和asprintf 。

使用scanf的返回值

 do { count++; if (scanf("%s", &text[count]) != 1) break; } while (strcmp(text[count], end) != 0);