简体   繁体   English

为什么 printf 在循环中只打印一次,仅用于第一个输入?

[英]why is printf prints just once in a loop, only for the first input?

void hexToDec(){
    char numHex, numDec;
    int isNum, isLowAf, isHighAf;
    printf("Enter a reversed number in base 16:\n");
    scanf("%c", &numHex);
    while(numHex != '\n'){
        isNum = isHighAf = isLowAf = 0;
        if(numHex >= 48 && numHex <= 57)
            isNum = 1;
        if(numHex >= 65 && numHex <= 70)
            isHighAf = 1;
        if(numHex >= 97 && numHex <= 102)
            isLowAf = 1;
        if(!isNum && !isLowAf && !isHighAf)
             printf("Error! %c is not a valid digit in base 16\n", numHex);
        //else - Hexadecimal to Decimal converter
        fflush(stdin);
        scanf("%c", &numHex);
    }
}

I can't use string.h or arrays[] this task and I need to check every input I get and print every char that isn't digit in base 16. The problem is that it only check the first letter I enter and print not valid for it.我不能使用string.h或 arrays[] 这个任务,我需要检查我得到的每个输入并打印每个不是以 16 为基数的字符。问题是它只检查我输入的第一个字母并打印对它无效。

for example:例如:

input:输入:

lds

output: output:

Error! l is not a valid digit in base 16

expected:预期的:

Error! l is not a valid digit in base 16
Error! s is not a valid digit in base 16

Also I can't figure out why the while loop doesn't stop after I click Enter.我也无法弄清楚为什么单击 Enter 后 while 循环没有停止。

fflush(stdin) is not standard C. fflush(stdin)不是标准的 C。 But on systems where it works (Windows), it will discard all the buffered input that hasn't yet been.但是在它工作的系统(Windows)上,它将丢弃所有尚未缓冲的输入。 So after scanning the first character l , this will cause ds to be discarded, and it will wait for you to type a new line of input.所以扫描完第一个字符l后,这会导致ds被丢弃,它会等待你输入新的一行输入。

Get rid of that call if you want it to process the remaining characters of the line.如果您希望它处理该行的剩余字符,请摆脱该调用。

The while loop is not exiting because of the space in the second scanf .由于第二个scanf中的spacewhile循环没有退出。

Would be a tad nicer if character constants are used instead of hard coded numbers.如果使用字符常量而不是硬编码数字会更好。

 while(numHex != '\n'){
    isNum = isHighAf = isLowAf = 0;
    if(numHex >= '0' && numHex <= '9')
        isNum = 1;
    else if(numHex >= 'A' && numHex <= 'F')
        isHighAf = 1;
    else if(numHex >= 'a' && numHex <= 'f')
        isLowAf = 1;
    if(!isNum && !isLowAf && !isHighAf)
         printf("Error! %c is not a valid digit in base 16\n", numHex);
    //else - Hexadecimal to Decimal converter
    //fflush(stdin);//undefined behavior
    scanf("%c", &numHex);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM