// A Demo file showing some of the things
// we can do with character variables

// Marc Chee (cs1511@cse.unsw.edu.au) June 2020 - March 2021

#include <stdio.h>

int main(void) {
    // we're using an int to represent a single character
    int character;
    // we can assign a character value using single quotes
    character = 'a';
    // This int representing a character can be used as either
    // a character or a number
    printf("The letter %c has the ASCII value %d.\n", character, character);

    // using getchar() to read a single character from input
    int input_char;
    printf("Please enter a character: ");
    input_char = getchar();
    printf("The input %c has the ASCII value %d.\n", input_char, input_char);
        
    // using putchar() to write a single character to output
    putchar(input_char);
    printf("\n");
    
    
    // reading multiple characters in a loop
    printf("Type in multiple characters, ending with Ctrl-D to stop.\n");
    int read_char;
    read_char = getchar();
    while (read_char != EOF) {
        printf(
            "I read character: %c, with ASCII code: %d.\n",
            read_char, read_char
        );
        read_char = getchar();
    }


}

Resource created Wednesday 27 January 2021, 01:16:16 PM, last modified Monday 15 March 2021, 03:54:34 PM.

file: char_demo.c


Back to top

COMP1511 21T1 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G