strcmp 用户输入和文件输入不匹配

Posted

技术标签:

【中文标题】strcmp 用户输入和文件输入不匹配【英文标题】:Strcmp user input and file input not matching 【发布时间】:2016-02-25 07:31:25 【问题描述】:

对于作业,我必须从包含目录列表的文本文件中删除一行。用户输入文件名并且必须删除包含文件名的目录。对于作业,我必须使用 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;

【问题讨论】:

您是否尝试使用打印或任何调试器进行调试? 我已经尝试调试,让它输出它正在比较的两个东西,在用户看来它们应该是相同的,但对程序来说却不是。 打印strlen的结果。我确定长度不同。 我有几点意见:你应该使用 std:string;你应该使用 stricmp。 @spartin503 简单提示:如果打印出用于调试的字符串,总是将它们括在引号中,这样您就可以看到空格! (比如cerr &lt;&lt; "'" &lt;&lt; variable &lt;&lt; "'" &lt;&lt; endl;)养成这个习惯,省去几个小时的痛苦…… 【参考方案1】:

它返回 -13

13 是回车的 ascii。 看来第二个参数最后包含一个额外的 CR。

解决方案Trim 字符串通过删除(或用'\0' 替换字符)参数字符串的所有尾随空格(“ctype.h”,isspace)字符。

【讨论】:

以上是关于strcmp 用户输入和文件输入不匹配的主要内容,如果未能解决你的问题,请参考以下文章

为啥我的文件内容/用户输入不匹配? (缺少chomp规范)[重复]

将用户输入与结构数组中的值进行比较

为啥从标准输入读取用户输入时我的字符串不匹配?

用户登录接口

C++:从文件/用户名和密码读取

显示来自用户输入的部分数组值匹配