【问题标题】:C - Strcmp() not working [duplicate]C-Strcmp()不起作用[重复]
【发布时间】:2016-07-17 10:33:13
【问题描述】:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{

const int SIZE = 100;

char input[SIZE];

while(1)
{
    fgets (input, SIZE - 2, stdin);          // input
    printf("%d", strcmp(input, "exit"));    //returining 10 instead of 0

    if(strcmp(input, "exit") == 0)
    {
        printf("SHELL Terminated\n");
        exit(0);    
    }

return 0;
}

我遇到了一个问题。如果我在input变量中输入exit,函数strcmp()返回10,但它应该返回0并退出程序,因为exit等于退出。但事实并非如此。

我找不到问题。

【问题讨论】:

  • 您是否尝试过先打印input 变量?
  • @cad 空字符空间...
  • 谷歌搜索你的确切标题会得到:“大约 60,500 个结果”,前三个条目是关于“换行”问题的三个 SO Q&A。
  • @Muzahir Hussain:首先,为什么要为 one 空字符保留 两个 字节?其次,fgets 已经知道在内部为空字符保留空间。

标签: c strcmp


【解决方案1】:

您得到10,因为您的输入字符串中有一个换行符。 10 返回值是该换行符的 ascii 值与您要比较的 "exit" 字符串文字的终止空字符之间的差异。

【讨论】:

    【解决方案2】:

    fgets 在读入缓冲区的字符串末尾追加一个换行符 (\n)。

    删除它使用

    char* newline = strchr(input, '\n');
    if (newline)
        *newline = '\0';
    

    As @WeatherVane mentionedfgets 的某些调用可能不会在缓冲区中设置换行符,因此我们需要检查strchr 是否返回NULL(未找到换行符)。

    【讨论】:

    • 如果文件的最后一行没有newline,或者如果传递给fgets 的输入缓冲区比文本行长度短,此方法将中断。
    • 是的,但是,alk 和 vlad 有更好的方法。
    • @WeatherVane ...我完全同意。 :-)
    • 是的,fgets 可以附加换行符。但是用strchr去搜索,简直是暴殄天物。
    • @AnT 怎么会是“暴行”?
    【解决方案3】:

    函数fgets 还包括换行符'\n',例如,如果数组中有足够的空间,则对应于按下的 Enter 键。

    您应该通过以下方式删除它

    fgets( input, SIZE, stdin );
    input[strcspn( input, "\n" )] = '\0';
    

    或者更安全

    if ( fgets( input, SIZE, stdin ) != NULL ) input[strcspn( input, "\n" )] = '\0';
    

    考虑到这段代码

    *strchr(input, '\n') = '\0';
    

    通常是无效的,因为数组中可以不存在换行符,函数strchr将返回NULL

    【讨论】:

      【解决方案4】:

      fgets() 保留'\n'。您可以将其从 input 中删除(请参阅其他答案)或将其添加到文字中

      strcmp(input, "exit\n")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-23
        • 1970-01-01
        • 1970-01-01
        • 2012-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多