gpt4 book ai didi

c - 警告 : comparison is always true due to limited range of data type

转载 作者:太空宇宙 更新时间:2023-11-04 05:14:10 26 4
gpt4 key购买 nike

我正在测试这个应该从用户那里读取输入的函数,但它会抛出一个段错误

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX_STRING_LENGTH 10

int
readinput(char *input)
{
int c;
int i=0;
while((c=getchar()) != EOF && c != '\n') //Here is where the warning occurs.
{
input[i]=c;
i++;
}
input[i]=0;
if(strlen(input)>0)
{
if(isalpha(input[0]) && input[1]=='-' && isalpha(input[2]) && strlen(input)==3)
return 0;
else if(!strcmp(input, "quit"))
return 1;
else if(!strncmp(input, "save ", 5))
return 2;
else if(!strcmp(input, "undo"))
return 3;
}
return -1;
}

int main()
{
char *str;
printf("write a string\n");
int nr=readinput(str);
printf("%d\n", nr);
printf("%s\n", str);
return 0;
}

我确实注意到了我犯的愚蠢错误,但仍然是段错误,为什么?

最佳答案

这是因为 EOF 被定义(在我的编译器中)为 -1 而 char 是无符号字节。所以它总是!=

关于c - 警告 : comparison is always true due to limited range of data type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13303528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com