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

您应该使用fgets()逐行读取文件,然后使用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 回答
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 回答