Asaf
Asaf

Reputation: 17

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.

for example:

input:

lds

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.

Upvotes: 0

Views: 42

Answers (2)

Lily AB
Lily AB

Reputation: 400

The while loop is not exiting because of the space in the second scanf.

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);
}

Upvotes: 0

Barmar
Barmar

Reputation: 781058

fflush(stdin) is not standard C. But on systems where it works (Windows), it will discard all the buffered input that hasn't yet been. 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.

Get rid of that call if you want it to process the remaining characters of the line.

Upvotes: 2

Related Questions