我希望能够执行检查,其中我将输入文件的第一个字符与某个字符进行比较(在本例中假设为
*
),然后如果它们不匹配则打印“Hello world”。
我可以从文件中读入。但是strcmp()
不允许我比较输入文件字符和我声明的字符。
int main(void)
{
FILE *file = fopen("text.txt", "r");
char c;
char compare[] = "*"
do
{
c = fgetc(file);
compare = strcmp(c,compare); //Something is wrong here I think.
printf("result: %d \n", compare);
}
while (c != EOF);
fclose(file);
return 0;
}
它们之间存在差异或两个字符串同时以空字符终止。 如果你想比较两个字符你想要做的就是直接比较两个字符
char * string1 = "string1";
char * string2 = "string2";
if (string1[0] != string2[0])
puts("hello world");
或者你的情况
if (c != compare[0])
puts("hello world");
但是因为你的比较只是一个字符,而你只想比较 1 个字符,所以你最好将它声明为一个字符,比如通过做
char compare = '*';
...
if (c != compare)
puts("hello world");
#include <stdio.h>
int main(void)
{
FILE *file = fopen("text.txt", "r");
char c;
char compare = '*';
do
{
c = fgetc(file);
if(c == compare)
printf("result: %c \n", compare);
}
while (c != EOF);
fclose(file);
return 0;
}
strcmp
比较两个字符串。 您正在尝试将单个字符与空终止字符串
"*"
进行比较。我什至不确定您发布的这段代码是否会编译,因为strcmp
需要两个char *
作为参数,但您传递的是char
作为第一个参数。此外,您期望
strcmp
的返回值到字符指针,但是
strcmp
返回一个 int
.这里是对strcmp
的参考。如果您不确定某个标准库函数,您应该使用这个网站。但是,在这种情况下,我敦促您找到一个不同的、更简单的解决方案来解决您的问题(提示:strcmp
不需要比较
char
s),并练习阅读编译器警告/错误!