C - Strcmp()不起作用

Muz*_*ain 1 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;
}
Run Code Online (Sandbox Code Playgroud)

我正面临一个问题.如果我在变量中输入exitinput,则函数strcmp()返回10,但它应该返回0并退出程序,因为exit等于exit.但事实并非如此.

我找不到问题.

Car*_*rum 8

得到的10是因为输入字符串中有换行符.在10返回值是换行字符的ASCII值和的终止空字符的区别"exit"字面你比较字符串.


Vla*_*cow 6

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

您应该删除它,例如以下方式

fgets( input, SIZE, stdin );
input[strcspn( input, "\n" )] = '\0';
Run Code Online (Sandbox Code Playgroud)

或者更安全

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

考虑到这段代码

*strchr(input, '\n') = '\0';
Run Code Online (Sandbox Code Playgroud)

通常是无效的,因为数组中可能缺少新的行字符,函数strchr将返回NULL.


cad*_*luk 5

fgets将newline(\n)字符附加到读入缓冲区的字符串的末尾.

使用删除它

char* newline = strchr(input, '\n');
if (newline)
    *newline = '\0';
Run Code Online (Sandbox Code Playgroud)

正如@WeatherVane所提到的,有些调用fgets可能没有在缓冲区中设置换行符,所以我们需要检查是否strchr返回NULL(没有找到换行符).