0

More About printf and scanf (Part 2)


This is part 2 of the printf and scanf. I will talk about scanf usage in this post. Before go to the source code, take a note that I replaced some fflush(stdin) statements to two-line dummy statements which is explained in the source code below. The purpose of these is to clean up any previous input values without use another function other than scanf since fflush(stdin) is not used to flush input. According to this page and the materials I learned, the scanf function does not use often by the programmers. However, since I’m still learning, I will learn from the basics.

/*
 *
 * scanf.c
 * Demonstrate the use of the scanf() function
 * By Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int x;
 float y;
 char string[100];

 /*
 *
 * String input
 *
 */

 printf("Enter one word: ");
 // %s in scanf will only store one word. This means that it will not store the remaining words after the first space.
 // Note there is no & before string. String is the only variable type that do not need &
 scanf("%s", string);
 printf("The word you entered was >>%s<<n", string);

 // Below are the dummy lines to clean up the input value
 while(getchar() != 'n' && getchar() != EOF)
 printf("%s", string);

 printf("Enter many words: ");
 // Read up to a newline (multiple words)
 // ^ means not, which ^n means do not read new line
 scanf("%[^n]", string);
 printf("The text you entered was >>%s<<n", string);

 /*
 *
 * Integer input
 *
 */

 printf("Please enter a number: ");
 // Note the &
 scanf("%d", &x);
 printf("The number you entered was %dn", x);

 /*
 *
 * Character input
 * The following code is self-explanatory
 *
 */

 while(getchar() != 'n' && getchar() != EOF)
 printf("%s", string);

 printf("Please enter a single character: ");
 scanf("%c", &string[0]);
 printf("The character that you entered was '%c'n", string[0]);

 while(getchar() != 'n' && getchar() != EOF)
 printf("%s", string);

 printf("Please enter 4 characters: ");
 // Note that characters are not limited to letters. It can be numbers.
 scanf("%4c", &string[0]);
 printf("The characters you entered were >>>%c%c%c%c<<<n", string[0], string[1], string[2], string[3]);

 /*
 *
 * Floating-point input
 *
 */

 printf("Please enter a decimal number: ");
 scanf("%f", &y);
 printf("The number you entered was %fn", y);

 fflush(stdin);
 getchar();
}


There are no posts related to More About printf and scanf (Part 2).