CSC 161 Schedule Readings Labs & Projects Homework Deadlines Resources

Reading Data

We explore how a program can read different types of data from an input source like the keyboard.

Reminder

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>

Introduction to scanf

  1. Copy program scanf-example.c to your account, compile it, and run it.
    1. 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.
    2. 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?

    3. 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.

    4. 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.

    5. Run the program yet again.
      • if you are using a 64-bit computer (i.e., any MathLAN computer), enter the following data:
        • 01234567890123456789012345678901234567890123456
        • 01234567890123456789012345678901234567890123456
      • if you are using a 32-bit computer, enter the following data:
        • 0123456789012345678901234567890123456
        • 0123456789012345678901234567890123456
      What output is generated? Can you guess why? Note that the first string has 47 characters and the second string has 37 characters.
  2. Write a short program that asks for your name, stores your name using scanf, then prints the word "hello" and your name. Be sure NOT to use "%s" as your scanf format string, but use a length-limiting version. What happens when you type as input more than the length of input that is allowed?

Reading Multiple Values

  1. Each of the following programs reads two numbers using scanf, using different format variations. Save, read, compile, and run each program 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 Individual Characters

  1. Program get-3-char.c reads three characters from the keyboard and prints them.
    1. Copy get-3-char.c to your account, and compile it, and briefly describe what it does.
    2. Run the program, entering abc on the same line (no spaces), and describe what happens.
    3. Run the program, entering a b c on the same line (with spaces between the letters), and describe what happens.
    4. Run the program, trying to enter a on one line, b on a second line, and c on a third line. What happens? In the output, the first line appears as $a$, but the second and third lines contain a single dollar sign. Why?
    5. Run the program, trying to enter ab on one line, c on a second line. Again, explain what happens and why.
    6. In the program, replace
      ch1 = getchar();
      ch2 = getchar();
      ch3 = getchar();
      by
      scanf ("%c", &ch1);
      scanf ("%c", &ch2);
      scanf ("%c", &ch3);

      and change the declarations of ch1ch3 from int to char.

      Does the program behave the same (i.e., for b–e), or is something different? Why or why not?

    7. In the previous step, replace the three scanf statements by the single statement:
      scanf ("%c%c%c", &ch1, &ch2, &ch3);
      Again, determine whether the program behaves as before or does something else, and explain what you observe.

Reading One Line, Character by Character with getchar

  1. Program getchar-example.c reads and prints a line of characters from the keyboard. As you observed in Step 1, the single-character printing function putchar, like getchar, deals with a single character per call.
    1. Copy getchar-example.c to your account, compile it, and briefly describe what it does.
    2. What happens when you enter more than one letter? Why?
    3. What happens if you do not enter a letter, but simply press Enter?

      Recall that getchar gets a single character; blank space and newline characters are considered viable characters.

    4. What happens when the program receives no input? You can simulate this by taking the input from an empty file:
      ./getchar-example < /dev/null
    5. Why do you think the line
      putchar ('\n');

      is included?

      Like getchar, putchar takes a single character. The function putchar prints a single character to the "standard" output stream called stdout.

  2. Although reading and printing one character at a time is sometimes useful by itself, a more common approach is to collect a line of characters in an array. This practice is illustrated in the getchar-line-example.c program.
    1. Copy getchar-line-example.c to your account, compile it, and briefly describe what it does.
    2. Examine the first loop. Why does putchar (a) precede a = getchar()? Why does putchar ('\n') appear after the loop? What happens if you move putchar ('\n') inside the loop?
    3. Examine the second loop. What is the purpose of the index variable? The loop condition involves both an assignment and a comparison. Explain how that works and why it is used. Why is the statement line[index]=0 placed after the loop?
    4. What happens in the output if the line line[index-1]=0 is deleted from after the second loop? Explain.
    5. Can the line buffer be overflowed? Amend the termination test of the while loop to fix any such problem.

Reading Values within Applications

  1. Write a program to read a person's height in feet and inches and print the person's height in centimeters (1 inch = 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.

Reading, Comparing, and Processing Strings

  1. 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>" (angle brackets 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 will be helpful.

    1. Test whether the program works as intended by entering words that match, and words that do not match.
    2. Enter words which are identical, except for capitalization (for example, "apple" versus "apPle"). What happens? Why do you get this result?
    3. Modify your program so that it makes all the letters in a word the same case, and rerun your tests.
  2. Write a program that does the following:
    • Declares a character array one larger than some upper size limit.
    • Reads a number from the keyboard (likely using scanf).
    • Clears any whitespace after the number from the first line of input, perhaps using something like the following code:
      int ch;
      do {
        ch = getchar();
        if (ch == EOF) {
          /* do something reasonable when there is an error or no more input.
                  print an error message, exit the program, etc. */
        }
      } while (ch != '\n'); /* Read until a newline is found */
    • Reads the specified number of characters from the keyboard (up to the size limit).
    • Adds a null character at the end of the array.
    • Prints the resulting string.
  3. Modify the characters as they are entered in the previous program, so that it sets each letter to the opposite case when placing it in the string. Note that <ctype.h> has functions that compare types and modify letter cases. For example:
    • appleAPPLE
    • AlPhAbEtaLpHaBeT
    • X-Rayx-rAY

Additional Practice

  1. Read input data to control the robot as follows.
    1. 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.
    2. Modify your program so that it continues, prompting for input and beeping, until the time entered is 0.
    3. Further modify the program to count the number of beeps, and when the time entered is 0, print the number of beeps before exiting the program.
  2. 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.
  3. 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.
    • Use the quadratic formula
    • 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 write a C program that uses the math.h library, your source code must "include" it,
      #include <math.h>
      and your compile command must explicitly link the library, using the flag -lm. For example,
      cc -Wall -lm -o quadratic quadratic.c