alexanderbowen
alexanderbowen

Reputation: 85

Terminate a loop with specific characters

I want to write a program that will terminate a loop with a specific character such as "Q" or "//" but can't seem to figure it out. here is the specifics

"A program that will compute the average of a set of decimal numbers provided by the user. The program will ask the user to enter numbers one at a time, and when the user enters q it stops and spits out the sum"

But this requires the user to enter in integers and if I enter a "Q" or "//" the program breaks and spits out junk. How do I do this?

The problem im running into is how to do this without asking for two different inputs

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

//variables
double avg, num;
char q;

int main()
{
    double sum = 0;
    int count1 = 0;
    while (q != 'q') {
        cout << "Enter a number" << endl;
        cin >> num;
        cin >> q;
        sum += num;
        count1 += 1;
    }
    avg = sum / count1;
    cout << "Sum: " << sum << endl;
    cout << "Count: " << count1 << endl;
    cout << "Average: " << avg << endl;
    return 0;
}

Upvotes: 0

Views: 181

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129504

Assuming your assignment is really what you describe, then you will need to read a string, and then convert to double.

Something like this will work:

std::string s;
std::cin >> s;
if (s == "Q" || s == "//") { ... do stuff ... }
else
{
    std::stringstream ss(s);
    double d;
    if (!(ss >> d))
    {
        std::cout << s << " doesn't appear to be a number..." << std::endl;
    }
    ... do whatever with d ... 
}

I'm not writing the code for you, just providing some snippets to help you along.

Upvotes: 3

Related Questions