### strings and vectors

The numbers I input are not adding at the end. May I know why?

 ``1234567891011121314151617181920212223242526272829303132333435`` `````` #include #include using namespace std; int main( ) { int n,i,temp; int sum = 0; vector v; cout << "Enter a list of positive numbers.\n" << "Place a negative number at the end.\n"; int next; cin >> next; while (next > 0) { v.push_back(next); cout << next << " added. "; cout << "v.size( ) = " << v.size( ) << endl; cin >> next; } for(i=0;i> temp; sum += temp; } cout << "\n\nSum of the " << n << " numbers entered by the user is : "<< sum << endl; cout << "\n\n\n"; return 0; }``````
Last edited on
You never initialize n.

Usually it's easier to read the code (and less chance of forgetting to initialize) if you declare the variables as late as possible (when you know what value to give to them) rather than at the beginning of the function.
Last edited on
thank you so much!
 ``123456789101112131415`` ``````#include #include #include int main() { std::vector v; std::cout << "Enter a list of positive numbers.\n" << "Place a negative number at the end.\n"; for (int next; (std::cin >> next) && next >= 0; v.push_back(next)) std::cout << next << " added.\n"; std::cout << "\n\nSum of the " << v.size() << " numbers entered by the user is : " << std::accumulate(v.begin(), v.end(), 0) << "\n\n"; }``````

Obviously you don't need to use a vector to store the numbers before they are totalled. A running total could be kept as they were entered:

 ``1234567891011121314`` ``````#include int main() { unsigned sum {}; unsigned noNums {}; std::cout << "Enter a list of positive numbers.\n" << "Place a negative number at the end.\n"; for (int next; (std::cin >> next) && next >= 0; ++noNums, sum += next) std::cout << next << " added.\n"; std::cout << "\n\nSum of the " << noNums << " numbers entered by the user is : " << sum << "\n\n"; }``````

Last edited on
Topic archived. No new replies allowed.