对于作业,我必须从具有目录列表的文本文件中删除一行。用户输入文件名,包括该文件名的目录必须删除。对于分配,我必须使用char数组。我有一个问题,当strcmp应该返回0时返回-13,但这仅在应该删除的那一行之后还有另一行时才会发生。这里是有问题的代码:
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;
}
返回-13
13是回车的ascii。看来第二个参数在末尾包含一个额外的CR。
解决方法通过删除参数字符串的所有尾随空格(“ ctype.h”,isspace)字符(或用替换字符)来
修剪'\0'
字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句