Advertisement
janac

Sum any number of integers using a vector

Nov 8th, 2021 (edited)
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5. // Enter any number of integers and
  6. // display how many numbers there are and the sum.
  7. int main()
  8. {
  9.     vector<int> numbers; // The values entered.
  10.     int sum = 0; // The sum of the values entered.
  11.     string input; // Input.
  12.     int current_number = 0; // Input converted to integer.
  13.  
  14.     cout << "Enter any number of integers, one at a time.\n"
  15.         "Enter 'x' on a line by itself when you're finished." << endl;
  16.     cin >> input; // Store input.
  17.     while (input != "x") // Unless you're finished.
  18.     {
  19.         current_number = stoi(input); // Convert the input to an integer
  20.         numbers.push_back(current_number); // Store the integer.
  21.         sum += current_number; // Add the number to the total.
  22.         cin.clear(); // Reset error flags.
  23.         cin.ignore(100, '\n'); // Ignore up to the new line.
  24.         cout << "Enter your next number: " << endl; // Display the sum.
  25.         cin >> input; // Store input.
  26.     }
  27.     cout << endl; // Blank line.
  28.     cout << "The sum of " << numbers.size()
  29.         << " numbers is: " << sum << endl; // Display the sum.
  30.  
  31.     return 0;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement