I'm new to C++. I have written a program that allow user to add in file to my data folder. But now I want to also allow user to delete the files. So in the case below, it will displayed a list of available files from the data folder. The user chooses the file by entering the number, for example, [i] to delete the file from the list and also delete in the data folder. I have tried writing codes to delete it, but I got this error "Debug Assertion Failed". Is there something wrong with my delete?
case 'D':
case 'd':
myfiles = getFiles();
cout << "Current available objects:" << endl;
for (int i = 0; i < myfiles.size(); i++)
cout << '[' << i << ']' << ' ' << myfiles[i] << endl;
cout << endl << "Enter file number to delete or \"end\" to exit:";
while (cin >> str)
{
if (str == "end")
break;
input = str2int(str);
if (input >= 0 && input < myfiles.size())
{
//Delete object
newname = ExePath() + "/data/" + myfiles[input];
name = new char[newname.size() - 1];
strcpy(name, newname.c_str());
remove(name);
//Print out the available objects
cout << "\nCurrent available objects:" << endl;
for (int i = 0; i < myfiles.size(); i++)
cout << '[' << i << ']' << ' ' << myfiles[i-1] << endl;
cout << endl << "Enter file number to delete or \"end\" to exit:";
}
else cout << "Invalid input." << endl;
}
break;
I think it's this loop:
When
iis 0, then you are trying to accessmyfiles[-1]. Ifmyfilesis not an object of a very strange class which overloadsoperator[]in an unusual way, but is instead just a normalstd::vector(99% more likely :)), then this is undefined behaviour, i.e. anything can happen (including the error message you see).As a side note, you are performing pointer operations instead of using real C++ strings (i.e.
std::stringobjects) consistently. Which is surprising, because you already seem to have astd::stringthere (newname), and you seem to know how to use it together with (old / legacy / C) functions requiring achar const *, namely with itsc_str()member function. Why don't you just writeremove(newname.c_str())?