// 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
// Marc Chee (cs1511@cse.unsw.edu.au), June 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 use EOF (end of file)
// 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) {
int result = scanf("%d", &numbers[num_count]);
if (result == EOF) {
// user has ended input
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]) != EOF) {
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 Tuesday 23 June 2020, 01:08:11 AM, last modified Tuesday 23 June 2020, 01:08:44 AM.
file: scanfDemo.c