0

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;
}
4
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by caut_baia
0

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

0

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.

Edited by jonsca: lern too rite

0

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 :(

Edited by NathanOliver: n/a

0

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," "));

  }
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.