3: User I/O

What We Will Cover


Continuations

Homework Questions?

Viewing WebCT Assignment and Exercise Results

Questions from last class?

How do comments contribute to good code?
  1. They provide hints to the compiler.
  2. They provide hints to the interpreter.
  3. They provide hints to the user.
  4. They provide hints to the programmer.

3.1: Problem Solving and Pair Programming

Objectives

At the end of the lesson the student will be able to:

  • Describe the purpose of programming
  • Create simple algorithms
  • Discuss the pros and cons of pair programming

3.1.1: Problems and Problem-Solving

  • Recall that programming is about solving problems using a computer program
  • When you first start computer programming, you may think that the hard part is translating your ideas into code
  • This is definitely not the case
  • The most difficult part is finding a solution to the problem
  • After finding a solution, translating your solution to code is a routine, almost mechanical, task

Defining a Problem

  • You first start solving a problem by understanding its requirements
  • Understanding the requirements often includes analysis of:
    1. Data inputs: files, user interaction
    2. Data manipulation of data: computations, selection
    3. Data output: output device, formats
  • If the problem is complex, you divide it into sub-problems
  • Each sub-problem is then analyzed to understand its requirements
  • At the end, you should write (or type) a definition of the problem, or sub-problems, in your own words

3.1.2: Algorithms

  • After you define a problem, you write out a sequence of steps to solve the problem
  • These steps should be written in a natural language such as English or Español
  • Instructions like these are referred to as an algorithm
  • Algorithm -- a sequence of instructions to solve a problem.

Total cost of Items

Problem: Total the cost for a list of items.

Algorithm:

  1. Write the number 0 on a blackboard (or other media)
  2. Do the following for each item on the list:
    • Add the cost of the item to the number on the board
    • Replace the old number by this sum
  3. Announce that the answer is the number written on the board

Play Tic-Tac-Toe

Problem: Play the game of tic-tac-toe.

Algorithm:

  1. Select 2 players
  2. Draw a big #
  3. Player 1: draw an X in one of the squares
  4. Player 2: draws an O in some square
  5. Continue alternating between the players until either:
    • Someone has three letters in a row or diagonal
    • All the squares are filled.

Observations about Algorithms

  • Notice that the sequence of steps you follow in a algorithm is often important
  • Also, notice that algorithms often require making one or more decisions
  • In addition, algorithms often contain repetition: steps that are repeated

3.1.3: Pair Programming

  • Defining problems and developing algorithms on your own is often difficult
  • You may work with others, though it is best to try to define a problem and develop an algorithm on your own first
  • What you cannot do is show other people your homework solutions or code
  • However, when you translate the algorithms into code, you often run into syntax errors that are difficult to see
  • It would be nice to get help from another human in these cases
  • However, the instructor prohibits asking most people from looking at your code
  • What is the solution to this problem?
  • Pair Programming for Homework Assignments

Defining Pair Programming

  • Pair programming is two people work together on one computer at the same time
    • Exactly two people: not one nor three or more
    • Exactly one computer: not two or more
  • The driver operates the keyboard and mouse
  • The navigator actively participates in the programming
    • Analyzes the design and code to prevent errors
    • Also in charge of using printed reference materials like textbooks
  • Each person "drives" about half the time
    • Physically get up and move positions when switching roles
  • At most 25% of your time is spent working alone
    • Any work done alone is reviewed by the other person
  • The object is to work together and to learn from each other
  • You cannot divide the work into two pieces with each partner working on a separate piece

Why Pair Program?

  • Students who pair program report:
    • Higher confidence in a program solution
    • More satisfaction with programming
  • Instructors report higher retention rates

More Information

3.1.4: Best Practices

  • You may choose any other student in this class for a partner
  • Both of your names appear on the assignment
  • When choosing partners and working together, certain practices help you perform better
  • Pair-programmers are more successful when they have similar experience levels
  • Need to find a partner with whom you can easily exchange ideas

Getting Along

More Information

3.1.5: Summary

  • Programming is about solving problems using a computer program
  • To develop a computer program, you start by defining the problem(s) to solve
  • Once a problem is well defined, you develop an algorithm to solve it
  • An algorithm is a sequence of instructions to solve a problem
  • Since defining problems, developing algorithms and implementing algorithms is hard, you can work with a partner
  • Use some care when choosing a pair-programming partner to maximize your success
  • In addition, both you and your partner should read: All I Really Need to Know about Pair Programming I Learned In Kindergarten

Exercise 3.1

  1. Label this exercise: Exercise 3.1
  2. Submit all exercises for this lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in your exercise3.txt file.

Specifications

  1. We will count off and divide into separate groups
  2. Within your group, exchange email addresses so that you can send the answer to this exercise to each other.
  3. As a group, take 10 minutes to define the problem and describe an algorithm for counting the number of statements in a program.

3.2: Interactive Keyboard Input

Objectives

At the end of the lesson the student will be able to:

  • Get user input from the command line
  • Prompt users when requesting input

3.2.1: About Keyboard Input

  • For programs used infrequently, easy to put data directly in the code
  • For instance, to calculate the average of four numbers:
#include <iostream>
using namespace std;

int main() {
    double average = (32.6 + 55.2 + 67.9 + 48.6) / 4;
    cout << "Average = " << average << endl;

    return 0;
}
  • Easy to include the four numbers with the code operating on those numbers
  • However, you must recompile the program if you change any number
  • More convenient for users to enter data without recompiling a program
  • This section discusses how you can get user input while a program is running

3.2.2: Using cin

  • To get data from a user, we use cin
  • cin >> num;
  • cin is an input stream bringing data from the keyboard
  • '>>' (extraction operator) points toward where the data goes
  • Waits on-screen for keyboard entry
  • Value entered at keyboard is 'assigned' to num
  • You can list more than one variable in a cin statement
  • cin >> v1 >> v2 >> v3;
  • No literals allowed for cin
  • Must input 'to a variable'

3.2.3: Prompting Users

  • Always 'prompt' user for input
  • int numOfDragons;
    cout << "Enter number of dragons: ";
    cin >> numOfDragons;
    
  • Note that you do not put a newline at the end of the prompt
  • The prompt waits on the same line for keyboard input as follows:
  • Enter number of dragons: ____
  • Where the underscore above denotes where keyboard entry is made
  • Every cin should have a cout prompt
  • In addition, often a good idea to echo what the user typed
  • For example:
  • #include <iostream>
    using namespace std;
    
    int main() {
        double num1, num2;
        cout << "First number: ";
        cin >> num1;
    
        cout << "Second number: ";
        cin >> num2;
    
        cout << num1 << " + " << num2 << " = "
             << num1 + num2 << endl;
    
        return 0;
    }
    
  • Maximizes user-friendly input/output

3.2.4: Summary

  • cin is an input stream bringing data from the keyboard
  • '>>' (extraction operator) points toward where the data goes
  • When designing I/O:
    • Prompt the user for input
    • Echo the input by displaying what was input

Exercise 3.2

Use the following program for this exercise:

#include <iostream>
using namespace std;

int main() {
    double num1, num2;
    cout << "First number: ";
    cin >> num1;

    cout << "Second number: ";
    cin >> num2;

    cout << num1 << " + " << num2 << " = "
         << num1 + num2 << endl;

    return 0;
}

Record the answers to the following questions in your exercise3.txt file:

  1. Compile and run the above program.
  2. Enter some numbers to make sure the program works.

  3. Enter the phrase "bad data" at an input prompt.
  4. Q1: What results did you see? Why?

  5. Remove the code #include <iostream> and recompile the program.
  6. Q2: What error message did the compiler give you?

3.3: Formatted Output

Objectives

At the end of the lesson the student will be able to:

  • Display program output to the console
  • Format numbers during output

3.3.1: Output Using cout

  • cout is an output stream sending data to the monitor
  • The insertion operator "<<" inserts data into cout
  • What can be outputted?
  • Any data can be outputted to display screen
    • Variables
    • Constants
    • Literals
    • Expressions (which can include all of above)
    int numberOfGames = 12;
    cout << numberOfGames << " games played." << endl;
    
  • 2 values are outputted:
    • Value of the variable numberOfGames
    • Literal string " games played."
  • Note that you can have multiple values in one cout

3.3.2: Newlines in Output

  • Recall that '\n' is escape sequence for the char "newline"
  • A second method is to use the object endl
  • Examples:
  • cout << "Hello World!\n";
  • Sends string "Hello World!" to display and escape sequence '\n'
  • cout << "Hello World!" << endl;
  • Same result as above

3.3.3: Decimal Formatting

  • Numbers may not display as you'd expect!
  • double price = 78.50;
    cout << "The price is $" << price << endl;
    
  • If price (declared double) has value 78.5, you might get:
  • The price is $78.5
  • We must explicitly tell C++ how to output numbers in our programs!
  • 'Magic Formula' to force decimal sizes:
  • cout.setf(ios::fixed);     // fixed notation, not scientific
    cout.setf(ios::showpoint); // show decimal point
    cout.precision(2);         // show 2 decimal places
    
  • Now all future values have exactly two digits after the decimal place
  • For example:
  • cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    
    double price = 78.5;
    cout << "The price is $" << price << endl;
    
  • Now results in the following:
  • The price is $78.50

3.3.4: Error Output with cerr

  • cerr works same as cout
  • Provides a mechanism for distinguishing between regular output and error output
  • cerr << "Error: it's a mistake! " << endl;
    
  • Allows you to re-direct output streams
  • Most systems allow cout and cerr to be 'redirected' to other devices
    • For instance: line printer, file, error console, etc.
    • Does not work for Windows

3.3.5: Summary

  • cout is an output stream sending data to the monitor
  • The insertion operator "<<" inserts data into cout
  • There are two ways to output a new line:
  • cout << "Hello World!\n";
    cout << "Hello World!" << endl;
    
  • cout includes special tools to specify the output of type double
  • cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    
  • You can use a separate output stream named cerr
  • Allows you to redirect error messages to a separate device

Exercise 3.3

Using the following starter code, write a program that asks the user for a number and then displays the number in both currency and percent formats like that shown below:

Enter a number: 12.3
As a dollar amount: $12.30
As a percent: 12.3%

Note that you will need to have two cout.precision() statements in your code.

Copy an example run of your code into exercise3.txt file.

#include <iostream>
using namespace std;

int main() {
    double num;
    cout << "Enter a number: ";
    cin >> num;

    // Put your code here

    return 0;
}

3.4: Working With Strings

Objectives

At the end of the lesson the student will be able to:

  • Identify string types from their literal representation
  • Assign strings to variables
  • Concatenate strings
  • Use string operators and member functions
  • Display string variable data
  • Collect user input of type string

3.4.1: Introduction to Strings

  • The string class allows the programmer to use strings as a basic data type
  • Defined in the string library and std namespace
  • #include <string>
    using namespace std;
    
  • Included automatically with our version of g++

Literal Strings

  • A string is a sequence of characters
  • String literals are made by enclosing a sequence of characters in double quotes
  • For example:
  • "Hello"  "b"  "3.44159"  "$3.95"  "My name is Ed"
  • Double quotes used to mark the beginning and end of a string are not stored
  • Notice that the string "3.44159" could be expressed as a double by removing the quotes
  • However, a computer stores these two values very differently
  • double type 3.44159 is stored in eight bytes using the IEEE 754-1985 standard
  • String type "3.44159" is stored as ASCII characters
  • Both data types are useful for solving problems

3.4.2: String Assignments

  • You can assign literal strings to string objects using the assignment operator
  • string s1 = "Hello Mom!";
    cout << s1 << endl;
    
  • You can assign other string objects to a string object
  • string s1, s2;
    s1 = "Hello Mom!";
    s2 = s1;
    cout << s2 << endl;
    

3.4.3: Joining Strings

  • You can join two string objects together using the '+' operator
    • The join operation is called concatenation
    string s3 = s1 + s2;
  • The string s3 now has the contents of both s1 and s2
  • cout << s3 << endl;
    
  • You can also mix string objects and literal strings
  • string s1, s2;
    s1 = "Hello Mom!";
    s2 = s1;
    string s3 = s1 + " " + s2;
    cout << s3 << endl;
    

3.4.4: String Functions

  • Once you create a string, you can use its member functions
  • Syntax for calling a member function of an object:
  • stringName.function(arguments)

Some Commonly-Used Functions

  • at(int): Returns a char at the specified index.
  • string text = "ABCDEF";
    char ch = text.at(2);
    cout << ch << endl;
    
  • length(): Returns the length of the string
  • string s = "Hello";
    cout << s.length() << endl;
    

3.4.5: Output Using cout

  • You can use the insertion operator << to output objects of type string
  • string s = "Hello Mom!";
    cout << s << endl;
    
  • You can mix string and other data in one cout statement

3.4.6: String Input

Using cin

  • You can use the extraction operator >> to input string data
  • string s1;
    cout << "Enter something: ";
    cin >> s1;
    cout << "You entered: " << s1 << endl;
    
  • However, there are some complications
  • >> skips whitespace and stops on encountering more whitespace
  • Thus, you only get a single word for each input operation
  • If a user types in "Hello Mom!", you would only read "Hello" and not " Mom!"
  • This is because cin >> s1 works as follows:
    1. Skips whitespace
    2. Reads characters
    3. Stops reading when whitespace is found

Input Using getline()

  • To read an entire line you can use function getline()
  • Syntax:
  • getline(istreamObject, stringObject);
  • For example:
  • string line;
    cout << "Enter a line of input:\n";
    getline(cin, line);
    cout << line << "END OF OUTPUT\n";
    
  • getline stops reading when it encounters a '\n'
  • Also, you can set getline to stop reading on another character
  • For example:
  • getline(cin, line, '?');
    

Using ignore()

  • Recall that cin >> s1:
    1. Skips whitespace
    2. Reads characters
    3. Stops reading when whitespace is found
  • Thus cin >> will leave a '\n' character in the input stream
  • This can lead to mysterious results in code like the following:
  • int n;
    string line;
    cout << "Enter your age: ";
    cin >> n;
    cout << "Enter your name: ";
    getline(cin, line);
    cout << "You entered: " << n << " " << line;
    
  • To get around this problem you can use member function ignore()
  • Syntax:
  • cin.ignore(numCharsToIgnore, charToStopAfterReading);
  • For example:
  • int n;
    string line;
    cout << "Enter your age: ";
    cin >> n;
    cin.ignore(1000, '\n');
    cout << "Enter your name: ";
    getline(cin, line);
    cout << "You entered: " << n << " " << line;
    
  • The following line reads up to 1000 characters or to '\n'
  • cin.ignore(1000, '\n');

3.4.7: Summary

  • You make string literals by enclosing characters in double quotes
  • Strings are an object type in C++ and operate differently than primitive types
  • To concatenate two strings, use the "+" operator
  • You use functions of the string object for some operations
  • Type string can be input and output with cin and cout
  • To read an entire line, you need to use the getline function
  • getline(cin, line);
  • Sometimes cin >> can leave a '\n' character in the input stream
  • To get around this problem you can use member function ignore
  • cin.ignore(numCharsToIgnore, charToStopAfterReading);
  • For example:
  • int n;
    string line;
    cout << "Enter your age: ";
    cin >> n;
    cin.ignore(1000, '\n');
    cout << "Enter your name: ";
    getline(cin, line);
    cout << "You entered: " << n << " " << line;
    

Exercise 3.4

Take 5 minutes to complete the following:

  1. Start a text file named exercise3.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 3.4
  4. Submit all exercises for today's lesson in one file unless instructed otherwise
  5. Complete the following and record the answers to any questions in exercise3.txt.

Specifications

  1. Start your text editor and enter the following code:
  2. #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        string firstName = "Your", lastName = "Name", fullName;
        fullName = firstName + " " + lastName;
        cout << "Full name: " << fullName << endl;
        return 0;
    }
    
  3. Save the file as "nameapp.cpp".
  4. Q1: Which lines of code declare strings?

  5. Compile and execute the code.
  6. Q2: Which line of code concatenates strings?

  7. Add code to display the length of the full name.
  8. Q3: What function did you use to determine the length of the string?

  9. Change the program to get the first and last name from the user.

Either copy your modified program to exercise3.txt or submit your program as a separate file along with exercise3.txt.

Wrap Up

Home | WebCT | Announcements | Day Schedule | Eve Schedule
Course info | Help | FAQ's | HowTo's | Links

Last Updated: September 16 2004 @16:27:42