0

fscanf()複数の行から整数を含むファイルを読み取るために使用する必要があります。

最初の整数はすべての行で役に立ちません。残りは読む必要があります。

私はこのようにやっています

do {
    fscanf(fs1[0],"%d%c",&x,&y);
    //y=fgetc(fs1[0]);
    if(y!='\n') {
        printf("%d ",x);  
    }
} while(!feof(fs1[0]));

しかし無駄に。例えば、

101 8 5 
102 10 
103 9 3 5 6 2 
104 2 6 3 8 7 5 4 9 
105 8 7 2 9 10 3 
106 10 6 5 4 2 3 9 8 
107 3 8 10 4 2 

私たちは読まなければなりません

8 5
10
9 3 5 6 2 
2 6 3 8 7 5 4 9
8 7 2 9 10 3
10 6 5 4 2 3 9 8
3 8 10 4 2
4

3 に答える 3

2

ファイルを文字列で読み取った後 ( fgets ) 、 (strtok)を使用して文字列を分割し、 (sscanf)を使用して整数を読み取ることができます。

ストク:

char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
}

sscanf :

int number = 0;
if(sscanf(pch, "%d", &number) ;
于 2013-06-29T11:40:46.277 に答える
0
    do{
        fscanf(fs1[0], "%d%c",&x,&y);//ignore first data.
        while(2==fscanf(fs1[0], "%d%c", &x, &y)){
            printf("%d ", x);
            ch = fgetc(fs1[0]);//int ch;
            if(ch == '\n' || ch == EOF){
                printf("\n");
                break;
            } else
                ungetc(ch, fs1[0]);
        }
    }while(!feof(fs1[0]));
于 2013-06-29T16:04:19.547 に答える
0

を使用fgets()してファイルを 1 行ずつ読み取り、次に を使用して数値を解析する必要がありますsscanf()。その後、各行の最初の番号を好きなだけスキップできます。

次に例を示します。

#include <stdio.h>
#include <string.h>

int main() {
    char fname[] = "filename.txt";
    char buf[256];
    char *p;
    /* open file for reading */
    FILE * f = fopen(fname, "r");
    /* read the file line-wise */
    while(p = fgets(buf, sizeof(buf), f)) {
        int x, i = 0, n = 0;
        /* extract numbers from line */
        while (sscanf(p+=n, "%d%n", &x, &n) > 0)
            /* skip the first, print the rest */
            if (i++ > 0)
                printf("%d ", x);
        printf("\n");
    }
}

参考のため:

于 2013-06-29T11:32:01.127 に答える