Search code examples
cwhile-loopgetchar

Where is my error? (Converting number bases)


My program reads in a number and converts it to another base. It ignores all white space.

I am getting the wrong answer; however it works (without ignoring white space) if I remove the first while loop. Here is my code for base conversion:

 while ((d = getchar()) == '\n' || d == ' ' || d == '   ') {

    }

 while (((d = getchar()) != EOF) && (d != '\n') && (d!= ' ') && (d!='   ')) {
    if (a<=10) {
        if ((d-'0')<0 || (d-'0')>=a) {
            printf("Invalid number!\n");
            return 0;
            }
        num = num*a + (d-'0');
        printf("%d\n", num);
        }

    else {
        if (d >= 48 && d<= 57) {
            num = num*a + (d-'0');
            printf("%d\n", num);
        }
        else if (d>=97 && d<a+87) {
            num = num*a + (d-87);
            printf("%d\n", num);
        }
        else if (d>=65 && d<a+55){
            num = num*a + (d-55);
            printf("%d\n", num);
        }
        else {
            printf("Invalid number!\n");
            return 0;
        }

    }
}

Solution

  • You gobbled your first digit off your number. Use a do loop to reuse the last good read.

    while ((d = getchar()) == '\n' || d == ' ' || d == '   ') {
    
    }
    
    if (d != EOF) do {
        /* ... */
    } while (((d = getchar()) != EOF) && (d != '\n') && (d!= ' ') && (d!='   '));