【问题标题】:Loop doesn't work in C programming循环在 C 编程中不起作用
【发布时间】:2013-11-07 22:42:25
【问题描述】:

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

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吗?

标签: c file fgets


【解决方案1】:

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

改变你的测试:

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

【讨论】:

  • 我希望对“零努力查阅任何类型的文档”有一种特殊的反对意见......无论如何都很好。
【解决方案2】:

这应该可行:

#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',所以你也必须匹配它。

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 即使这样也行不通,因为 fgets() 保留了换行符。
    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 2013-06-25
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    相关资源
    最近更新 更多