0

I'm working on a program in C in which it will request a response, then use the first appearance of a digit (using isdigit() ) and then assign it to a variable for later use. After testing a bit I realized it was taking the ascii value for 10, which is line feed. Here is the code snippet.

    while(isdigit(ch) == 0){
                ch = getchar();
        }
        ch = getchar();
        star = ch;//value is being detected as 10, which is line feed.

I tried casting ch to int when assigning it to star, which did not change the resulting value of 10. Is my issue within the assignment of ch, or is it poor syntax?

Nora H
  • 3
  • 3
  • Note that the correct type for ch is int, since that's what getchar returns, and what isdigit accepts. – stark Mar 14 '22 at 20:32

1 Answers1

0

YOur problem is that you see a digit, then you read the next character

    while(isdigit(ch) == 0){
            ch = getchar();
    }
    ch = getchar(); <<<======

Just use the value in ch that you have already, plus you need to convert '0' to 0, not the same thing

    while(isdigit(ch) == 0){
            ch = getchar();
    }
    int inp = ch - '0';
pm100
  • 48,078
  • 23
  • 82
  • 145
  • 1
    `while (isdigit(ch) == 0) { ch = getchar(); }` will cause an infinite loop if there is no digit before the end of file. You must test for `EOF` in and after the loop. – chqrlie Mar 14 '22 at 23:00