我怎么能在同一行上得到我的程序的所有总和?

Zor*_*eth 2 c++ io

我试图在程序结束时将所有输出打印在一行上.我怎么能做到这一点?目前,在输入变量后直接打印总和,看起来像这样:

3
100 8
108
15 245
260
1945 54
1999
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像这样:

3
100 8
15 245
1945 54

108 260 1999
Run Code Online (Sandbox Code Playgroud)

这是我目前的代码:

#include <iostream>
using namespace std;

int main()
{
    int pairs = 0;
    cin >> pairs;

    for (int i=0,num1=0,num2=0; i < pairs; i++)
    {
        cin >> num1 >> num2;
        cout << num1 + num2 << " ";
    }
}
Run Code Online (Sandbox Code Playgroud)

Log*_*uff 5

起初,目前还不清楚你在问什么,但我找到了你.你在同一个循环中进行输入和输出.你需要一个输入和一个输出循环和一个容器:

#include <iostream>
#include <vector>
using std::cout;
using std::cin;

int main()
{
    int pairs = 0;
    cin >> pairs;
    std::vector<int> sums; // vector to hold sums, your int sum was unused
    sums.reserve(pairs);

    for(int i = 0; i < pairs; ++i)
    {
        // better initialize these variables here, otherwise they might
        // equal to previous input if this input fails
        // (you should declare them in inner-most scope possible anyway)
        int num1 = 0, num2 = 0;
        cin >> num1 >> num2;
        sums.push_back(num1 + num2); // do not cout, append the value to the sums instead
    }

    for(auto x : sums)
        cout << x << " "; // finally print the whole vector
}
Run Code Online (Sandbox Code Playgroud)