我不确定该如何表达我要问的问题。在C ++中,使用stdio.h头文件而不是iostream,我如何做到这一点,以便在任何时候按下转义键都会终止程序?是否可以在程序顶部添加一次,还是必须将其分别添加到每个循环/条件循环中?下面是我的代码(sleep()函数仅用于视觉加载/计算效果):

#include <stdio.h>
#include <math.h>
#include <windows.h>

void repeat();
void quadratic()
{
    double a, b, c;
    double ans[2];
    printf("-Arrange your equation in the form aX^2+bX+c \n-Enter the value of a: ");
    scanf("%lf", &a);
    printf("-Enter the value of b: ");
    scanf("%lf", &b);
    printf("-Enter the value of c: ");
    scanf("%lf", &c);
    double radical=((b*b)-(4*a*c));
    double root=sqrt(radical);
    double negB=(-1)*b;
    double denominator=2*a;
    if(denominator==0)
    {
        printf("Calculating");
        Sleep(100);
        printf(".");
        Sleep(100);
        printf(".");
        Sleep(100);
        printf(".");
        Sleep(100);
        printf("\nError: Denominator must be non-zero.\n \n \n");

    }
    else if(radical==0)
    {
        ans[0]=negB/denominator;
        printf("Both roots are equal: both values are X=%lf\n \n \n", ans[0]);

    }
    else if(radical<0)
    {
        printf("Calculating");
        Sleep(100);
        printf(".");
        Sleep(100);
        printf(".");
        Sleep(100);
        printf(".");
        Sleep(100);
        double r,i;
        radical*=-1;
        r=negB/(2*a);
        i=sqrt(radical)/(2*a);
        printf("\nBoth roots are imaginary numbers.\n");
        printf("Non-real answer(s): X=%lf+%lfi X=%lf-%lfi\n \n \n",r,i,r,i);

    }
    else
    {
    ans[0]=(negB+root)/denominator;
    ans[1]=(negB-root)/denominator;
    printf("Calculating");
        Sleep(100);
        printf(".");
        Sleep(100);
        printf(".");
        Sleep(100);
        printf(".");
        Sleep(100);
        printf("\nX=%lf, X=%lf\n \n", ans[0], ans[1]);
    }
    repeat();

}
void repeat()
{
    quadratic();
}
int main(void)
{
    quadratic();
    return 0;
}

最佳答案

stdio中使用的终端可能是行缓冲的
(煮熟的)。如果是这样,则通过scanf检查转义键将
不行。

查看这些网址:

Capture characters from standard input without waiting for enter to be pressed

scanf not reading input

CURSES或NCURSES将检测转义键(ASCII字符27),具体取决于
在终端类型上。

可以在WINDOWS中使用此代码检查ESCAPE
键。

    #include <conio.h>
    #include <ctype.h>

    int ch;

    _cputs( "Type 'Y' when finished typing keys: " );
    do
    {
      ch = _getch();
      ch = toupper( ch );

          if (ch != 27) {
           _cputs( "CHARACTER: " );
           _putch( ch );
           _putch( '\r' );    // Carriage return
           _putch( '\n' );    // Line feed
      }

    } while( ch != 27 );

关于c++ - 处理非输入键击?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28703598/

10-10 19:45