|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/may27/scanf.c
#include <stdio.h>
int main(){
/*
declaring a few integers
and character arrays
*/
int a, b, c, e, f, g;
char j[64];
char d[64];
char h[64];
char i[64];
/*
The character arrays above will hold up to 64 characters
we specify the number of characters we want to hold inside
the brackets
*/
printf("1. Enter a number: ");
scanf("%d", &a); /*
we're telling scanf to expect 1 integer.
since we are dealing with integers, we
need the & (the address-of operator) in front
of where we are going to store the integer
*/
printf("2. Enter two numbers: ");
scanf("%d %d", &b, &c); //telling scanf to expect 2 integers
printf("3. Enter a word: ");
scanf("%s", j); /*
here, we're telling scanf to expect 1 string,
since this is a string, we do not need the & in
front of the variable.
*/
printf("4. Enter a number and a word: ");
scanf("%d %s", &e, d); //telling scanf to expect an integer and a string, in that order
// you can mix and match what inputs you want scanf to take
printf("5. Enter two words: ");
scanf("%s %s", h, i); //telling scanf to expect two strings
//printing everything out here
printf("1. %d\n", a);
printf("2. %d %d\n", b, c);
printf("3. %s\n",j);
printf("4. %d %s\n", e, d);
printf("5. %s %s\n",h, i);
/*
keep in mind that scanf ignores everything after the space key, so if you
want scanf to accept more than 1 word per input, you need to tell scanf
exactly how many words you are going to give it. the examples above illustrate
that.
so if you want scanf to accept 3 strings you do this:
scanf("%s %s %s", a, b, c);
likewise, if you want scanf to accept more than 1 number or even a mix of numbers
and strings, you have to tell scan through the format strings that you intend to do
that
also, order matters with scanf as well,
scanf("%d %s", &a, b); - scanf expects an integer and a string in that order
scanf("%s %d", c, &d); - scanf will expect a string and an integer in that order
*/
}
|