Laboratory Exercise on Input with scanf
Perspective
As explained in the Reading data with scanf that accompany this module, when a user types data as input to a program, the user types a sequence of characters. Within a program, the code may proceed in one of two ways:
- read each character separately (subsequent processing may group one or more characters together), or
- use capabilities of C to read a group of characters as another type of data (e.g., read several characters as a number).
This lab focuses on the second approach, using the library function scanf to handle the reading of several types of data. The next session explores the first approach of character-by-character reading.
Goals
The goal of this lab is to explore how a program can read different types of data from the keyboard using scanf.
Reminders
The scanf function (in the stdio.h library) directs the machine to read values for one or more variables from the keyboard. For each desired value, scanf requires
-
information in a format string indicates how the characters typed by the user will be interpreted (e.g., as an integer, as a double, etc.), and
-
the address of a variable where the value read is to be stored.
-
As with printf, format information is collected together as an initial string parameter.
-
Using our experience from previous work with functions and parameters, parameters to scanf involve reference parameters (e.g., with an ampersand &), so the function scanf can place data at the location of an int or double.
Some exercises in this lab utilize strings operations. In such cases, be sure to include the following lines at the beginning of your code:
#include <stdio.h> #include <string.h>
Work Started in Class
-
Copy scanf-example-1-2.c from today's reading on scanf.
-
Uncomment the code for Example 1. Then compile and run the program with the input string
K2.71828 H 3.141592
-
Rerun Example 1 using different spacing for the input and explain the output produced. For example, you might remove all spaces from the input line.
-
Replace the comment for the code for Example 1 and uncomment the code for Example 2. Then repeat the above steps 1a and 1b.
-
-
Copy scanf-example-3.c from today's reading on scanf.
-
Uncomment the code for Variation 3a. Then compile and run the program with the input string
12:34:56
and rerun the program with the input
12 : 34 : 56
In each case, explain the output produced.
-
Replace the comment for the code for Variation 3a and uncomment the code for Variation 3b. The repeat the above step 2a.
-
-
Copy program scanf-example.c to your account, compile it, and run it.
-
Review scanf-example.c and write a short description of how it works. In your description, explain why an ampersand (&) is required for reading the number variable but is not needed for the input variable.
-
Write a short program that asks for your name, stores your name using scanf, then prints the word "hello" and your name.
-
Run the scanf-example.c program again, except this time enter two numbers (one for the initial number and one for the word). Does the program still work? Why?
Hint: what type does scanf assign input to in your code?
-
Run the scanf-example.c program, using a phrase as input (e.g. "down the hill"). What is the result?
Recall that scanf assigns input to a variable; when assigning input to a string, a blank space is not considered to be part of a string by scanf.
-
Run the scanf-example.c program one more time — this time entering two names (one for the initial number and one for the word). Does the program still work? Why?
Hint: again, consider what types scanf is assigning.
-
Run the program yet again.
-
if you are using a 32-bit computer, enter the following data:
- 0123456789012345678901234567890123456
- 0123456789012345678901234567890123456
-
if you are using a 64-bit computer, enter the following data:
- 01234567890123456789012345678901234567890123456
- 01234567890123456789012345678901234567890123456
What output is generated? Can you guess why? Note that the string has 37 characters.
-
-
Reading Multiple Values
-
Each of the following programs reads two numbers using scanf, using different format variations.
Click on each program, save it, compile it, and run it with the suggested input variations. For each test case, explain what values are read and why the scanf assigns the given values to the variables.
Reading Values within Applications
-
Write a program to read a person's height in feet and inches and print the person's height in centimeters (1 inch = approximately 2.54 centimeters). The output of the program should present an equation of the form:
5 feet 6.2 inches = 168.15 centimeters
That is, the number of feet should be given as an integer, the number of inches to 1 decimal place, and the number of centimeters to 2 decimal places. One space should separate each number from text or the equal sign.
-
Write a program that reads the radius of a circle and prints the circle's area and circumference in the format illustrated below:
radius area circumference 2.5 19.63 15.71
That is, the radius, area, and circumference should appear under headings, the radius should be printed to 1 decimal place, and the area and circumference to 2 decimal places.
-
Write a program that reads the coefficients a, b, c of a quadratic equation: a x2 + b x + c = 0, and prints the roots of the equation to two decimal places.
Notes:
- Use the quadratic equation (ask the instructor if you have forgotten this).
- For simplicity, you may assume that b2 – 4 a c ≥ 0.
- C's square root function is called sqrt and is defined in C's math.h library.
- To link a C program with the math.h library, your compile command must include the flag -lm. (For example, "gcc -lm -o quadratic quadratic.c".)
Homework
Reading and Comparing Strings
-
Some programs perform different actions based on the entered information. For instance, programs that change a password often require the user to enter the new password twice to guard against typos. If the input is not the same for both entries, the password is not changed. Write a short program that prompts the user to enter a word, then prompts the user to retype the word. If the input matches, the program should print out the line "The entered word was (word)" (parentheses not included). If the input does not match, the program should print out a line which includes both entries.
Hint: the <string.h> function strcmp (char * str1, char * str2); compares two strings, and
-
returns a negative number if str1 comes
before str2 in dictionary order (upper/lower case
matters)
Examples: strcmp("cat", "dog") < 0
strcmp("that", "this") < 0 -
returns 0 if the strings match.
Examples: strcmp("cat", "cat") == 0
but strcmp("cat", "cAt") ≠ 0 (lower case a and upper case A are different) -
returns a positive number if str1 comes
after str2 in dictionary order (upper/lower case
matters)
Examples: strcmp("dog", "cat") > 0
strcmp("this", "that") > 0
-
Test whether the program works as intended by entering words which match, and words which do not match.
-
Enter words which are identical, except for capitalization (for example, "apple" versus "apPle"). What happens? Why do you get this result?
-
Modify your program so that it makes all the letters in a word the same case, and rerun your tests.
-
returns a negative number if str1 comes
before str2 in dictionary order (upper/lower case
matters)
Robot I/O
Write a short program that connects to the robot, asks for beep length and pitch, beeps for the assigned length and pitch, and disconnects from the robot.
Modify the program you wrote in the previous exercise so the program continues, prompting for input and beeping, until the time entered is 0.
Now modify the program you have written to count the number of beeps, and when the time entered is 0, print the number of beeps before exiting the program.
created 29 July 2011 by April O'Neill last revised 9 August 2011 by April O'Neill minor editing 9 October 2011 by Henry M. Walker modest expansion in initial section 19 October 2012 by Henry M. Walker minor editing 9 October 2013 by Henry M. Walker reworked 8-9 February 2014 by Henry M. Walker readings added 19 September 2014 by Henry M. Walker updated and reformatted 31 May 2016 by Henry M. Walker |
![]() ![]() |
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu. |