I dont understand why it doesnt work like the first vector i can input ok but the program just ends right after that, like it wont let me input values for the second vector.

#include<iostream>
#include<vector>

using namespace std;



int main ()
{
	vector<int> a1;
	vector<int> b1;

	cout << "Enter values for first vector, type Q to quit " ;
	
	int input1;
	while ( cin >> input1)
	{
		a1.push_back(input1);

	}
	
	
	cout << "Enter values for second vector, type Q to quit " ;
	
	int input2;
	while ( cin >> input2)
	{
		b1.push_back(input2);
	}


	return 0;
}

Recommended Answers

All 5 Replies

I belive you need to clear the input buffer before the second while loop

ive tried cin.clear(input1) and cin.ignor(input1) before my second while lopp and still no go

When you are entering a char it's causing the input stream to go bad. I would think clear() would take care of it but I wasn't able to get it to work. There's got to be some other trick to it that I'm not aware of.

The simplest solution is leave your code as it is, but have your user hit EOF (ctrl-z on windows/ctrl-d on *nix) when they are done entering each set of numbers.
Another option would be to take in your values as strings instead of integers and check for "Q". That requires you to parse the strings to get the integers out.

i think the problem is that you are typing q to quit which sets the cin error state. try resetting the cin states to normal after your first while loop try a differnt way of ending the loop.


[EDIT]

^^^^^^^^^^^ bet me :(

I only see you not passing through the first loop.. anyway you can study this for a bit

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

template <typename T> void input (T);

int main ()
  {
    int x;
    cout << "'q' to exit" << endl;
    input (x);
  }

template <typename T> void input (T a)
  {
    vector <T> avec;
    vector <T> bvec;
    int step=0;

    while (cin >> a)
      {        
        if (step%2==0) avec.push_back(a);
        else if (a=='q') break;
        else bvec.push_back(a);
        step++;
      }
    cout << "First vector holds: ";
    copy (avec.begin(),avec.end(),ostream_iterator<T>(cout," "));
    cout << "\n";
    cout << "Second vector holds: ";
    copy (bvec.begin(),bvec.end(),ostream_iterator<T>(cout," "));

  }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.