// A demo program using scanf
// This shows a little bit of using libraries and functions
// as well as how the output of a function can be used

// Using scanf, this is a series of different ways we
// can read in multiple inputs and store them in an array

// Marc Chee (cs1511@cse.unsw.edu.au), October 2020

#include <stdio.h>

int main(void) {
    int num_count = 0;
    int numbers[10] = {0};
   
    // scan in 10 numbers and store them in the array
    // Note that scanf returns the number of inputs read
    // so we're using this as the way to iterate the
    // counter. See if you can find the issues this causes!
    printf("Please enter 10 numbers for the loop.\n");
    while (num_count < 10) {
        num_count += scanf("%d", &numbers[num_count]);
    }
    
    // Another option for scanning 10 numbers
    // This is a pretty rough way to do this, but it's
    // interesting to note that scanf will ignore gaps
    // like spaces and newline (\n) in console input
    // in between numbers.
    printf("Please enter 10 numbers.\n");
    scanf(
        "%d%d%d%d%d%d%d%d%d%d",
        &numbers[0],
        &numbers[1],
        &numbers[2],
        &numbers[3],
        &numbers[4],
        &numbers[5],
        &numbers[6],
        &numbers[7],
        &numbers[8],
        &numbers[9]
    );
    
    // If we're looking to only take in values until
    // the input ends, we can check how many values
    // scanf read in as a way to end a loop of scanf
    printf("Please enter up to 10 numbers. Press Ctrl-D if you are finished.\n");
    num_count = 0;
    int keep_looping = 1;
    while (num_count < 10 && keep_looping) {
        // scanf will return the number of values it has
        // read in. We store that in result
        int result = scanf("%d", &numbers[num_count]);
        if (result != 1) {
            // We didn't receive a valid input, so we're ending
            keep_looping = 0;
        }
        // using result to increment num_count
        // this means that num_count will only go up if
        // scanf received a valid input.
        num_count += result;
    }
 
    // If we want to, we can even put the result of a function
    // into the "question" expression of a loop
    // Every time the while loop starts, the "question" function
    // will run. The result of the function will determine
    // whether the rest of the loop runs
    printf("Please enter up to 10 numbers. Press Ctrl-D if you are finished.\n");
    num_count = 0;
    while (scanf("%d", &numbers[num_count]) == 1) {
        num_count++;
    }
    
    // A loop to print out the contents of the array
    int i = 0;
    while (i < 10) {
        printf("%d, ", numbers[i]);
        i++;
    }
    printf("\n");
}

Resource created Wednesday 27 January 2021, 01:16:16 PM, last modified Monday 08 March 2021, 04:11:53 PM.

file: scanf_demo.c


Back to top

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