简体   繁体   English

C++ 入门第 5 版练习 3.20 向向量添加元素

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

I just started learning C++ with C-Prime 5th Edition.我刚开始使用 C-Prime 5th Edition 学习 C++。 And in problem 3.20 "Read a set of integers into a vector. Print the sum of each pair of adjacent elements".在问题 3.20“将一组整数读入一个向量。打印每对相邻元素的总和”。 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.我仍然无法弄清楚我的 VSCode 是否存在问题,或者我的代码在某处错误并溢出。 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.当我测试在 push_back 工作时打印出一些东西并且没有问题时,没有错误消息,代码只是在将元素添加到我猜的向量后停止。

#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.输入:1 2 3 4 5 然后代码停止。 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:该程序不知道您要输入多少个数字。也许编写一个只迭代 5 次的 for 循环,这样您就可以得到 5 个输入,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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