Sign in to follow this  

Copying character arrays

This topic is 4668 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Basically I am trying to read in a file line by line and store each line into an array as follows. char TempObjectName[32]; vector<char*> CompleteObjectList (0); ifstream infile; infile.open("ObjectList.dat"); while(!infile.eof()) { static short int i = 0; infile.getline(FirstWord, '\n'); strcpy(CompleteObjectList[i], FirstWord); cout << CompleteObjectList[i] << endl; i++; } infile.close(); The code compiles fine, but a runtime error occurs when I try to copy the array of characters into the CompleteObjectList. Any help is much appreciated. -Chris

Share this post


Link to post
Share on other sites
Quote:
Original post by bengaltgrs

strcpy(CompleteObjectList[i], FirstWord);
cout << CompleteObjectList[i] << endl;


First, you haven't created any items in the vector CompleteObjectList. You initialize it's length to zero items, so accessing any item in it is a no-no. Second, even if you did make it of any length, you haven't allocated any memory for the pointer contained in the vector, so the pointer contains a garbage address and accessing what it points to is a no-no aswell.

First you need to resize the vector so is't large enough to hold enough items for the index you use to access the vector with, and then you must allocate enough memory for the pointers in the vector. But since you're using vector, I see no reason you you're not using string aswell.

Something like this. Not tested so may not work without some modifications.

vector<string> CompleteObjectList (0);

ifstream infile;
infile.open("ObjectList.dat");

while(!infile.eof())
{
string n;
getline(infile, n);

CompleteObjectList.push_back(n);
}
infile.close();

Share this post


Link to post
Share on other sites

This topic is 4668 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this