【问题标题】:_stricmp is not comparing as expected_stricmp 未按预期进行比较
【发布时间】:2018-05-22 17:56:23
【问题描述】:

我写了这个简单的脚本,它让我发疯了。我不明白为什么我做的比较总是不一样。

这是我的代码:

int main()
{
        char test[]="boy";
        char test2[20];

        fgets(test2, 20, stdin);

        if (_stricmp(test2, test) == 0)
        {
            printf("the same");
        }
        else
        {
            printf("Not");
        }
    }

如果我插入“男孩”这个词,我还是会弄错。

有什么问题?

【问题讨论】:

  • fgets 包含尾随换行符,试试char test[]="boy\n";
  • @KeineLust 像魅力一样工作谢谢!!

标签: c string fgets


【解决方案1】:

所以看起来我们应该添加一个新行,然后效果很好

char test[]="boy\n";

【讨论】:

  • 你应该多解释一下。
【解决方案2】:

这已经回答了。但是将我的答案添加到@Jabberwocky 评论中。

该程序的问题不在于_stricmp,而在于fgets。当您输入“boy”时,test2 数组将被填充为 { 'b', 'o', 'y', '\n', '\0' },它不等同于 { 'b', 'o', 'y', '\0' }

C 库函数 char *fgets(char *str, int n, FILE *stream) 从指定流中读取一行并将其存储到 str 指向的字符串中。它会在读取任何 (n-1) 个字符、读取换行符或到达文件结尾(以先到者为准)时停止。

您有两种选择来解决此问题:

  • \n 添加到test 的末尾,使其变为char test[] = "boy\n";。如果您使用该字符串来做其他事情并且您不需要将\n 添加到它,这可能会很烦人。因此,我推荐第二种选择。

  • 读取输入后删除\n,然后进行比较。通常我会自己写GetString函数来解决这个问题,当用户输入的长度大于缓冲区时解决问题。

    void GetString(char *buffer, int count)
    {
        fgets(buffer, count, stdin);
        fseek(stdin, 0, SEEK_END); // Doesn't affect next fgets if user input was larger than buffer size.
        int length = strlen(buffer);
        if (buffer[length - 1] == '\n') buffer[length - 1] = '\0'; // Remove the newline.
    }
    

【讨论】:

  • 完全同意这种方法。而不是从错误中运行;正确对待应用程序的方法。
猜你喜欢
  • 2018-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多