I'm trying to enter integers for a and b and then print those integers put together. For example, entering 1 2 3 4 for a and 4 3 2 1 for b would yield: 1 2 3 4 4 3 2 1. I don't understand why my program isn't printing this. Whenever I enter -1, nothing happens. Am I doing the process wrong while the program is running? Help is appreciated.

#include <iostream>
#include <vector>

using namespace std;

vector<int> append(vector<int> a, vector<int> b)

{
    int n = a.size();
    int m = b.size();

    vector<int> c(n + m);

    int i;

    for (i = 0; i < n; i++)
        c[i] = a[i];

    for (i = 0; i < m; i++)
        c[n + i] = b[i];

    return c;

}
main()
{
    vector<int>a, b, c;
    int temp;

    cin >> temp;
    while (temp != -1) {
        a.push_back(temp);
        cin >> temp;
}

    cin >> temp;
    while (!cin.eof()) {
        b.push_back(temp);
        cin >> temp;
}

    c = append(a, b);
    for (int i = 0; i < c.size(); i++)
        cout << c[i] << " ";
    cout << endl;

}
有帮助吗?

解决方案

You have two loops, one to input the vector a and another to input b. Hitting -1 once would terminate only the first loop. The second one is terminated by an eof which you still haven't entered. So either enter an eof (specific to your system) or have the second loop terminate at -1 (in which case you'll need to enter -1 once more).

其他提示

You say

Whenever I enter -1, nothing happens.

That's because you reach the second cin >> temp statement at that time (just before while.eof() loop). That's when you start inputting values for b vector. You end that loop by entering EOF character in the stream (CTRL+Z on windows, CTRL+D on linux).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top