strings and vectors

Feb 23, 2022 at 5:07am
The numbers I input are not adding at the end. May I know why?

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
26
27
28
29
30
31
32
33
34
35

 #include <iostream>
#include <vector>
using namespace std;

int main( )
{
	 int n,i,temp;

    int sum = 0;
    vector<int> 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<n;i++)
    {
        cout << "Enter number" << i+1 << " :  ";
        cin >> 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 Feb 27, 2022 at 11:42am
Feb 23, 2022 at 5:24am
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 Feb 23, 2022 at 5:25am
Feb 23, 2022 at 8:12am
thank you so much!
Feb 23, 2022 at 10:00am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <vector>
#include <numeric>

int main() {
	std::vector<int> 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

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 Feb 23, 2022 at 10:01am
Topic archived. No new replies allowed.