For an assignment I have to delete a line from a text file that has a list of directories. The user inputs the file name and the directory including the file name has to be deleted. For the assignment I have to use char arrays. I am having a problem where strcmp returns -13 when it should return 0, but this only occurs when there is another line after the one that should be deleted. Here the code in question:
void deleteSong()
{
char userSongName[ENTRY_SZ], objectSongName[ENTRY_SZ];
cout << "Enter the name of a song you want to delete.\n";
cin.getline(userSongName, ENTRY_SZ);
Node* tempNode = musicList.GetFirstNode();
for (int n = 0; n < musicList.GetListLength(); n++)
{
strncpy(objectSongName, static_cast<Song*>(tempNode->data_)->GetSongName(), ENTRY_SZ);
cout << strcmp(userSongName, objectSongName) << endl;
if (!strcmp(userSongName, objectSongName))
{
ifstream songFileDir;
ofstream tempFileDir;
songFileDir.open(Song::songListFile_);
tempFileDir.open("temp.txt");
while (songFileDir.getline(userSongName, ENTRY_SZ))
{
if (!userSongName[0] == '\0')
{
if (strcmp(strrchr(userSongName, '\\') + 1, objectSongName))
{
tempFileDir << userSongName << endl;
}
}
}
songFileDir.close();
songFileDir.clear(ios_base::goodbit);
tempFileDir.close();
tempFileDir.clear(ios_base::goodbit);
remove(Song::songListFile_);
rename("temp.txt", Song::songListFile_);
musicList.RemoveThisLink(tempNode); //This calls a function that removes the node from the linked list.
delete tempNode;
return;
}
tempNode = tempNode->next_;
}
cout << "Song was not found.\n";
return;
}
It returns -13
13 is the ascii for Carriage return. It appears the second argument contains an extra CR at the end.
Solution
Trim the string by deleting (or replacing character with '\0'
) all the trailing whitespace ("ctype.h", isspace) character of the argument string.