Scanner for Integers (1)

Now it gets a bit more complex. Instead of individual digits, whole integer values should now be recognized in the input. You will be given a template for this. First, you should test it, and then we'll take a closer look at the details.

Change or add to your program as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
@ <stdio.hdr>

fn main()
{
    while (true) {
        local ch: int = getchar();
        if (ch >= '0' && ch <= '9') {
            local val: int = 0;
            while (ch >= '0' && ch <= '9') {
                val *= 10;
                val += ch - '0';
                ch = getchar();
            }
            printf("integer with value %d\n", val);
        } else if (ch == EOF) {
            break;
        } else {
            printf("ch = %d -> '%c'\n", ch, ch);
        }
    }
}

Tasks

  • Test the program with an input such as abc123xy42. Then it should correctly recognize that the integer values 123 and 42 occur:

    1
    2
    3
    4
    5
    6
    7
    MCL:session1 lehn$ ./a.out
    ab123xy42
    ch = 97 -> 'a'
    ch = 98 -> 'b'
    integer with value 123
    ch = 121 -> 'y'
    integer with value 42
    

    But the program is not working correctly yet. The 'x' was “swallowed”. In general, after each number, the following character is swallowed. We will address this later.

  • Now consider the part of the program that detects numbers in the input and ensures that the variable 'val' subsequently contains the corresponding numeric value. Consider this part:

    1
    2
    3
    4
    5
    6
    local val: int = 0;
    while (ch >= '0' && ch <= '9') {
        val *= 10;
        val += ch - '0';
        ch = getchar();
    }
    

    Explain to your neighbor (or let us explain to you) why, when inputting the sequence of digits '1', '2', '3', the variable 'val':

    • after the first loop iteration, has the value 1,

    • after the second loop iteration, has the value 12,

    • after the third loop iteration, has the value 123.

  • Use the *= and += operators in the while loop.

  • Now explain to your neighbor why a character is swallowed after each number. How the problem can be solved will be seen in the next step.