簡體   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