繁体   English   中英

如何使用fscanf()读取包含整数的文件?

[英]How to use fscanf() to read a file containing integer number?

我需要使用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

在读取字符串中的文件后,( fgets )可以使用(strtok)分割字符串然后使用(sscanf)读取整数。

strtok

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) ;

您应该使用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");
    }
}

以供参考:

    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]));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM