Assignment 7

due at midnight on   +40

In this assignment, you will input a series of positive numbers, and then output their sum and average. The series ends when the user types end instead of a number.

We will also do more sophisticated error-checking this time. If the user enters a line that cannot be interpreted as a number, then we should issue an error message and ignore that line, but then continue reading additional numbers.

Here is a sample run:

Computing a sum. Enter numbers one per line, or say 'end'.
8
2
0
-6
19
ten
?ignored
oops
?ignored
32
end
Sum is 55
Average is 9.16667

Text input

We know how to input numbers using cin, but in this program we will input text, so we can watch for the word end. The way that works is by declaring a string variable, and then using the getline function from <iostream>:

    string input; // declare variable
    getline(cin, input); // get one line of text from user

After calling getline, the variable input will contain the text the user typed. You can check for certain words using the equality operator == just like we do for numbers:

    if(input == "end")

Numeric conversion

After using getline to read text input, we will need to convert the text to a number. It’s possible this conversion can fail, as it does when the user types something like “ten.” To do the conversion, we’ll use a “string stream”. First we need to include a new library:

#include <sstream>

Then we can declare a “string input stream”, and use any string variable as the source:

    istringstream ss(input);

Finally, we can read data from the string stream with the usual >> operator. We can also embed this in an if condition to determine whether it worked:

    double num;
    if(ss >> num)
    {
        // Conversion worked, result is in `num` variable.
    }
    else
    {
        // Conversion did not work; issue error message
    }