1

だから私はこの入力ファイルを持っています:

1 2 3 4 5 6 7
3 2 4 1 6 5 7
***
1 1 2
1 1 2
***end of input***

整数の最初の 2 行をスキャンし、次にそれらをスキャンしてから、次の整数行をスキップし*てスキャンし、それらを使用して何かを実行したい (読み取りまでのループのように*)。

どうすればそれができますか?これが私のコードです:

int main(){
int i = 0, j ;
int temp[100];
char c, buf[20];
FILE *fp;
fp = fopen("input.txt", "r");
    if (fp != NULL){

            while (1 == fscanf(fp, "%d ", &temp[i])){
                i++;
            }   
                            // do something with the integers
    }
    else{
        printf("Cannot open File!\n");   
    }

return 0;
}

問題は、整数の最初の 2 行しかスキャンできないことです。の後に整数もスキャンしたい*

4

3 に答える 3

0

あなたはうまくやっていますが、唯一のことはファイル全体を読んでいないということです。これは、次のような簡単な変更を行うことで実現できます....

int main(){

    int i = 0, j;

    int temp[100];

    char c, buf[20];

    FILE *fp;

    fp = fopen("input.txt", "r");

    while ((c=getc(fp))!=EOF){  //here you are reading the whole file

        while (1 == fscanf(fp, "%d ", &temp[i])){
            i++;
        }   
        // do something with the integers
    }

    return 0;
}
于 2013-08-17T07:53:00.747 に答える