Scanner for Integers (2)

The issue with swallowed characters after a sequence of digits has been resolved in the following adjustment:

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

fn main()
{
    local ch: int = getchar();
    while (true) {               
        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);
            ch = getchar();
        }
    }
}

Tasks

  • Test that no characters are swallowed anymore.

  • In the program, there are two significant changes:

    • The variable ch is now declared before the while loop. The scope of the ch variable is now the entire function. The places where ch is overwritten are in lines 12, 19.

    • In the else branch of the if statement, getchar is now also called (line 19), and ch is overwritten. Test why this is necessary by commenting out this line, i.e., modifying it to

      1
      // ch = getchar();
      

      Then test the program again. Explain to your neighbor what goes wrong and why. Then revert the change.

  • The program should now also treat the '+' character specially. Add the following code after line 14:

    1
    2
    3
    } else if (ch == '+') {    
        printf("PLUS\n");                       
        ch = getchar();                     
    
  • Test the program, for example, with 12 + 4.

  • Modify the program so that:

    • '*' produces the output ASTERISK.

    • '(' produces the output LPAREN (for “Left Parenthesis”).

    • ')' produces the output RPAREN (for “Right Parenthesis”).

    • ';' produces the output SEMICOLON."