I have a little problem I can't figure out how to solve. I use the method open() to create a file. The method open only take a const* char (C-string) as parameter. I want the user to be able to choose the name of his file. The first time this works like a charm but the second time the user does this the old input is till there.
It's much simpler with an example. Here's the method:
void CarRegister::saveRegister()
{
system("clear");
std::cout << fileName; //Just for testing
std::cout << "Ange namnet på din fil: ";
std::cin.ignore();
std::cin.getline(fileName, 30); //The user types in the name of the file, for example "first"
ptrFileExtension = strcat(fileName, fileExtension); //The name of the file and a pre declared fileExtension (".txt") is added together and saved in a char pointer.
strcpy(fileNE, ptrFileExtension); //The fileNE is copied to a C-string
file.open(strcat(saveFolder, fileNE)); //The file are being created, works like a charm
for (int i = 0; i < carRegister.size(); i++)
{
file << carRegister[i].getBrand() << "\n";
file << carRegister[i].getModel() << "\n";
file << carRegister[i].getColor() << "\n";
file << carRegister[i].getHorsePower() << "hk\n";
file << carRegister[i].getModelYear() << "\n";
}
file.close();
}
When this is done it jump backs to a menu. In the menu the user wants to save another register and the program calls the saveRegister method again. Everything works fine but the old data the user typed in are still there!
The first time the file is named first.txt
The second time the file is named second.txtfirst.txt but it should be second.txt
Very grateful for help, hope you all understand my problem.
What is important to note is that strcat concatenates the contents of source to the destination, and then returns a pointer to destination (which is redundant, since you must already have a pointer to destination to be able to call strcat).
So, when you execute line 8, ptrFileExtension and filename are first.txt (more importantly, they both point to the same location in memory).
Also on line 10, saveFolder gets the contents of fileNE appended to it as well.
In both cases, strcat is changing the contents of fileName and saveFolder. You are inputting new data into fileName with line 7, but if you aren't resetting the contents of saveFolder (and the code you posted is not), then that is going to be a problem.