CS Behind the Curtain (CS195 2003S)

Lab: Input and Output

Summary: In this laboratory, we consider a number of key issues in C input and output. We focus primarily on input.

Contents:

Exercises

Exercise 1: A Simple Cat

Write a simple version of cat that simply echoes its input. Use getchar() as your primary input function.

Exercise 2: Varying Input

Here's a little program that is intended to read different kinds of input.

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

main()
{
  char ch;
  int i;
  char str[128];
  printf("Enter something: ");
  while ((ch = getc(stdin)) != EOF) {
    ungetc(ch, stdin);
    if (isdigit(ch)) {
      scanf("%d", &i);
      printf("You entered the number: %d\n", i);
    }
    else {
      scanf("%s", str);
      printf("You entered the string: '%s'\n", str);
    }
    printf("Enter something: ");
  } /* while */
  exit(EXIT_SUCCESS);
} /* main() */

a. Explain what the program is intended to do.

b. Do you notice any flaws in the program? If so, what are they and how might one correct them?

c. Compile and run the program to see if you detect other flaws.

Exercise 3: Another Simple Cat

Write another simple version of cat that simply echoes its input. Use gets() as your primary input function.

Exercise 4: Yet Another Simple Cat

Write another simple version of cat that simply echoes its input. Use scanf() as your primary input function.

Consder the following code:

  int i;
  float f;
  char str[128];
  if (scanf("$%d", &i))
    printf("Integer: %d\n", i);
  else if (scanf("#%f", &f))
    printf("Float: %f\n", f);
  else {
    scanf("%s", str);
    printf("String: %s\n", str);
  }

a. What does this code try to do?

b. Does it succeed?

c. Make it succeed.

 

History

Monday, 3 March 2003 [Samuel A. Rebelsky]

 

Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Fri May 2 14:19:53 2003.
The source to the document was last modified on Mon Mar 3 15:37:33 2003.
This document may be found at http://www.cs.grinnell.edu/~rebelsky/Courses/CS195/2003S/Labs/io.html.

You may wish to validate this document's HTML ; Valid CSS! ; Check with Bobby

Samuel A. Rebelsky, rebelsky@grinnell.edu