C - Strcmp() 不工作

标签 c strcmp

<分区>

#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 等于 exit。但事实并非如此。

我找不到问题。

最佳答案

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

关于C - Strcmp() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36291605/

相关文章:

c - 调用 fcntl() 的目的是什么,文件描述符为 -1,cmd 为 F_GETFL?

c - 如何转换 const char 字符串中的 uint64_t 值?

c - fgets 有更多的字符,它应该有

c - strcmp 的奇怪行为 [C]

使用 htonl(inet_addr(IP_str)) 将点分 IP 转换为整数返回 B 类和 C 类 IP 地址的负值

c - 链表和双指针

c - 使用 cat、tee 和 fifos 在多线程 C 程序中从 xterm 打印和读取

c - 如何比较 char 和 char 链表值?

c - 如何在 C 中从 char** 转换为 char*?

c - 如何搜索某个单词在文本文件中出现的次数