Variable/input data issue

Hey everyone,

What I am trying to do is write a c++ statement that will give the user the option of entering up to seven separate sets of floating point numbers, each separated by a space, but less than seven if the user has less than seven floating point numbers they would like to enter instead. I then manipulate the input data.

double food1A, food2A, food3A, food4A, food5A, food6A, food7A;

cout << "Enter up to seven transactions for your groceries each separated by a space: "; \\How do I make it so they can enter less than seven if they wanted to?

cin >> food1A >> food2A >> food3A >> food4A >> food5A >> food6A >> food7A;

double foodAtotal = food1A + food2A + food3A + food4A + food5A + food6A + food7A;
The easiest way is to use a vector (or array if you must) and have the user enter 0 (or some other unallowed value like a negative number) to stop early.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>

const size_t MaxValues = 7;

int main()
{
    std::vector<double> food;
    
    std::cout << "Enter up to " << MaxValues << " values. Enter 0 to stop.\n";
    for (double value; food.size() < MaxValues && std::cin >> value; )
    {
        if (value == 0) break;
        food.push_back(value);
    }

    double total = 0;
    std::cout << "\nYou entered:\n";
    for (double val: food)
    {
        std::cout << val << '\n';
        total += val;
    }
    std::cout << "The total is " << total << '\n';
}

Last edited on
Hello CWarrior987,

The only thing I could add to what dutch has said is if say lines 10 - 24 are in a loop then you would need to use food.clear(); to empty the vector before the next use.

Hope that helps,

Andy
Topic archived. No new replies allowed.