Reputation: 3
I am trying to make a program where you can add an item to a list, and each item has a specific value, and at the end it tallies them all up, but I can't find a way to allow a user to type in the name of a variable and it identifies it for use! I have already attempted to use cin >> but that didn't work!
Upvotes: 0
Views: 289
Reputation: 4452
You don't need to name the input values. The code below will return the sum of all numbers entered. Enter a blank line to end the list of numbers.
#include <iostream>
#include <sstream>
int main() {
std::string line;
int sum = 0;
while(true) {
std::getline(std::cin, line);
if (line.empty())
break;
int val;
std::istringstream(line) >> val;
sum += val;
}
std::cout << sum;
return 0;
}
If you do need to assign names to the input values for some reason, I suggest using a std::unordered_map
.
Upvotes: 1
Reputation: 643
The syntax to use cin is cin >> var;
not cin << var;
. Also, I recommend not using namespace std;
and do std::cin >> var;
Upvotes: 1