简体   繁体   中英

C++ Primer 5th Edition exercise 3.20 Adding Elements to a vector

I just started learning C++ with C-Prime 5th Edition. And in problem 3.20 "Read a set of integers into a vector. Print the sum of each pair of adjacent elements". I finish the code as below but my terminal does not execute the summary code. I still can not figure it out that is there a problem with my VSCode or my code is wrong somewhere and gets overflowed. When I tested to print something out whenever the push_back work and there is no problem with that, there is no error message, the code just stop after adding elements to the vector I guess.

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


int main()
{
    vector<int> a;
    int b;
    while(cin >> b)
    {
        a.push_back(b);
    }
    for (decltype(a.size())c = 0; c < (a.size() - 1); ++c)
    {
        auto d = a[c] + a [c+1];
        cout << "sum of " <<a[c]<<" and "<<a[c+1]<<" is: "<<d<<endl;
        d = 0;
    }
    system("pause");
    return 0;
    
}     

input: 1 2 3 4 5 then the code stop. Thankyou in advance.

You need a way to stop the program. The program doesn't know how many numbers you want to put in. Perhaps write a for loop that only iterates 5 times so you get 5 inputs like this:

int b;
for (int i = 0; i < 5; ++i)
{
    cin >> b;
    a.push_back(b);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM