繁体   English   中英

循环在C编程中不起作用

[英]Loop doesn't work in C programming

我想编写一个扫描每行并打印的程序。 当检测到特定线路时,此过程也应继续进行。 这是我的文件内容:

1
2
3
4
5
6
7
8
9

和代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *file;
int main(){
    file=fopen("numbers.txt","r");
    char line[10];

while(1){
         fgets(line,10,file);
         printf("%s \n\n",line);
         if(strcmp(line,"6")) break;
}

    fclose(file);
    system("pause");
    return 0;
}

但是循环不起作用,仅打印第一行。 问题出在哪儿?

如果字符串匹配, strcmp返回非零;如果匹配,则返回零。

更改测试:

if( 0 == strcmp(line,"6") ) break;

我想你的意思是if(! strcmp(line,"6")) break; (当字符串相等时,strcmp返回0)

这应该工作:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *file;
int main(){
    file=fopen("numbers.txt","r");
    char line[10];

    while(1){
             fgets(line,10,file);
             printf("%s \n\n",line);
             if(!strcmp(line,"6\n")) break;
    }

    fclose(file);
    system("pause");
    return 0;
}

您有两个问题,如果字符串相等,则第一个strcmp返回0,第二个fgets返回换行标记'\\ n',因此也必须匹配它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM