While loop(possibly vector) issues

Hey guys, so Im having trouble with this while loop. on my getlin (cin, n) after 1 loop through it skips the first character entered. I have no idea why, have never seen that before. Also when I'm leaving the loop my program crashes with the error "segmentation fault (core dumped). I've tried adjusting vector size but no effect. Any ideas anyone?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
vector<Wine*> wine;
bool more1 = true;

while (more1) {

	cout << "Enter wine name " ;
	string n;
	cin.ignore();
	getline (cin, n);  // after 1 loop skips first character entered
	if ( n == "no")
	{ more1 = false;
		cout << n;}
	else
	{
		cout << n;
		Wine* wine = new Wine(n);
	string wineryname;
	cout << "enter the winerys name:";
	getline (cin, wineryname);
	wine->setWineryName(find(winName, wineryname));
	wine[0].print();
	}
}
cin.ignore() discards a character from cin. The first character is getting skipped because you are telling the program to skip it. Get rid of cin.ignore().

As for the crash, you have two variables called wine, a vector and a pointer to a Wine. The pointer is shadowing (hiding) the vector. In any case, the new Wine is never added to the vector, so it is always empty. wine[0] crashes because you are asking for the first element of an empty vector.

Side note: why are you using pointers? Why not just use vector<Wine> and/or Wine wine(n);?
When I don't use cin.ignore() it skips the whole getline (cin, n). I read on stack overflow(I think) that this was a way to stop that. Do you have any recommendations on how to fix that?

Thank you! I figured out the crashing part! That's is exactly what was wrong with it!

As for why am I using pointers, this is a home work assignment and this is how my teacher wanted us to do it. Not my first choice on how I would be doing this
Last edited on
Topic archived. No new replies allowed.