#include <stdio.h>
#include <string.h>
int main()
{
FILE *pInFile;
pInFile = fopen("fileName.txt", "r");
char line[200];
while (fgets(line, sizeof(line), pInFile)) {
printf("\n%s", line);
if (strcmp(line, "C")==1)
printf("Success");
}
return 0;
}因此,程序的目标是在每次读取行后打印“成功”,在本例中是"C“。例如,我的文本文件如下所示
C
C
C
C我想把它打印出来
C
Success
C
Success
C
Success
C
Success但是,出于某种原因,它只打印了这个
C
Success
C
Success
C
Success
C忽略了最后的“成功”。我完全不知道它为什么要这么做。
发布于 2013-10-29 05:34:36
如果两个字符串相等,strcmp()将返回0。
尝试使用strcmp()将条件更改为:
if (line[0] == 'C') {
printf("Success");
}关于为什么要获得发布的输出的解释:
line中:
C\nstrcmp(line, "C") == 1时,它会成功,因为strcmp()返回>0,如果是第二个参数>第一个参数。strcmp()返回0,因为字符串是相等的,并且没有打印成功为了解决这个问题,要么做Gangadhar在他的帖子中的建议,要么做我在上面展示的。
发布于 2013-10-29 05:33:53
当字符串相等时,strcmp()的返回值为0。
发布于 2013-10-29 05:41:29
您可以使用strncmp()和比较一个字符
if (strncmp(line, "C" ,1)==0)
printf("Success");https://stackoverflow.com/questions/19650381
复制相似问题