Hello. I am trying to store information in a structure using this pointer loop method. If i try using the getline() method it seems to crash the program, and without it crashes if i enter more then 1 word.

Also when the last loop deleting the pointers goes off it crashes the program....Kinda confused why.

Help is appreciated :) Thanks

//Exc_6.cpp - practice with structures

#include<iostream>
#include<string>

using namespace std;

struct car
{
	string make;
	int year;
};

int main()
{
	int input, i;
	cout << "How many cars would you like to catalog? ";
	cin >> input;
	car ** numberOfCars;
	numberOfCars = new car * [input];
	for (i = 0; i <= input; i++)
	{
		numberOfCars[i] = new car;
		cout << "Please enter the make: ";
		cin >> numberOfCars[i]->make;
		cout << "Please enter the year made: ";
		cin >> numberOfCars[i]->year;
	}
	cout << "Here is your collection:" << endl;
	for (i = 0; i <= input; i++)
	{
		cout << numberOfCars[i]->make << " " << numberOfCars[i]->year << endl;
	}
	for (i = 0; i <= input; i++)
	{
		delete numberOfCars[i];
	}
	delete [] numberOfCars;
	system("PAUSE");
}

You are mis-naming things, and that is not helping. Also, you are using a list composed by (pointer to (pointer to car)). Why not just use a list composed by (pointer to car)? That is, you are using an array of (pointer to car) instead of just an array of car.

Finally, the difference is that you are not being careful when mixing >> and getline(). The first leaves the ENTER key in the input, while the second does not. After using >> you can get rid of the ENTER key by using cin.ignore().

unsigned numberOfCars;
cout << "How many cars would you like to catalog? ";
cin >> numberOfCars;
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );

car* listOfCars = new car[ numberOfCars ];

for (unsigned i = 0; i < numberOfCars; i++)
{
	cout << "Please enter the make: ";
	getline( listOfCars[ i ].make );
	cout << "Please enter the year made: ";
	cin >> listOfCars[ i ].year;
	cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
}

Remember, the user will always press ENTER after every input.

Hope this helps.

Edited 6 Years Ago by Duoas: n/a

That worked to help with the input, it does not fix the end crashing though......how am i supposed to delete it?

Unless you are still trying to delete something you shouldn't (which is everything except your original line 38), then please post your complete code again.

This article has been dead for over six months. Start a new discussion instead.