Question

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;

}
Was it helpful?

Solution

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).

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top