As a c++ beginner I’ve written the following code:
int main(void){
struct car{
char * make[200];
int manfYear;
};
int num=0;
cout << "How many cars do you wish to catalogue? ";
cin >> num;
car * Cars = new car [num];
for (int i=1;i<=num;i++){
cout << "Car #" << i << ":" << endl << "Please enter the make: ";
cin.getline(*Cars->make,200);
cout << "Please enter the year made: ";
cin >> Cars->manfYear;
}
My problem is that I can’t get my head round a problem where I get a segfault when running the program at the point I need to enter the model of the car. Can someone please explain what I’m doing wrong?
As far as I understand it I’m passing a pointer to the array “make” which should make it work. Is my understanding way off?
Thanks in advance
Dan
Four issues I see right away:
Issue 1
In your
struct, you have:char * make[200];In English, this is saying, “create an array of 200 pointers to character”, when I think you want to say, “create an array of 200 characters.” So you should have instead:
char make[200].Issue 2
You are looping by starting at
1. This will skip the first car in the array – remember arrays are zero-indexed. So you should have instead:for (int i = 0 ; i < num ; i++)and for display purposes, you could say:
cout << "Car #" << (i+1) << ":" << endl << "Please enter the make: ";Issue 3
Where you say:
cin.getline(*Cars->make,200);and
cin >> Cars->manfYear;Where in these lines are you specifying which car the user is populating? Nowhere. If you are looping with
i, then you need to actually mentioni. These should work:cin.getline(Cars[i].make,200);and
cin >> Cars[i].manfYear;Notice that we are using
., not->. This is because the items in theCarsarray are actual instances, not pointers. TheCarsarray is itself a pointer, but not its contents.Issue 4
All credit to @Ben C who pointed this out first: mixing the
>>operator withgetline()function oncincan lead to strange behavior, with leftoverCR‘s from>>going into thegetline()call. You could use either all>>(disadvantage: you don’t have the200limit enforced when reading the make) or allcin.getline()(disadvantage: you will have to use string buffers and then convert them for number of cars and year), or putcin.ignore()after each invocation of>>, like so:and
Again, all credit to @Ben C for noticing this first.
Last But Not Least
By convention, classes/structs have capital names, and variables have lowercase / camelcase names. Consider renaming the
structfromcartoCar, and the array fromCarstocars. In other words, the reverse of the capitalization you have right now.Finally, I concur with all the other posters here: you should consider using
stringinstead ofchararrays.