所以我希望能够执行检查,将输入文件的第一个字符与某个字符(在本例中假设为 *)进行比较,如果不匹配则打印“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;
}
最佳答案
strcmp 不比较字符,它是一个比较两个字符数组的循环直到它们之间存在差异或两个字符串同时以空字符终止。
如果你想比较两个字符你想要做的就是直接比较两个字符
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");
关于c - Q : How to compare char from text file in C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39949502/