Some basic IO

1
2
3
4
5
6
7
@ <stdio.hdr>

fn main() {
    while (true) {
        putchar(getchar());
    }
}

In <stdio.h>, the functions getchar and putchar are declared:

  • The getchar function reads a character from the keyboard and returns it as a return value.

  • The putchar function expects a character as an argument and displays it on the screen.

The program shown above, ex1.abc, does the following in an infinite loop: Read a character and then output it, read a character and then output it, and so on.

Tasks

  • Write the program in your preferred editor. Compile and execute it. Be aware of the following: Characters are obviously not immediately displayed but only after you press Return. For example, if you input 'a', 'b', 'c', and then Return, you will get the following output:

    1
    2
    3
    MCL:session1 lehn$ ./a.out
    abc
    abc
    

    You can use Control-C to (forcefully) terminate the program since it runs an infinite loop.

  • Our programs run within the shell. Therefore, the above statements about getchar and putchar were incorrect. More accurately (in terms of fuzzy logic) is:

    • getchar does not get input from the keyboard but from the shell.

    • putchar does not write characters to the screen but passes them to the shell for output.

    By default, the shell only forwards input to our program after you press Return. The purpose is to allow you to correct your input (for example, with Backspace) before pressing Return.

  • You can use the shell command stty to change this behavior so that input is immediately forwarded to the program:

    1
    2
    3
    MCL:session1 lehn$  stty -icanon min 1
    MCL:session1 lehn$  ./a.out
    aabbcc
    

    The shell is now “unusable” (we naturally want to be able to correct our inputs before pressing Return). Therefore, you should close and restart the terminal.

  • In the program, the keyword true was used as a condition. Internally, true is replaced with 1 by the compiler. Generally, any integer value can be used as a condition. The rule is “Zero is false, and everything else is true.”

    We test this using the workflow “Edit and save -> Compile -> Test”:

    • Change true to 42.

    • Change true to 2 > 1.