c - 从以空格分隔的文件中读取整数

标签 c arrays file-io

我有一个文件,其中包含这样的整数:

11_12_34_1987_111_       

其中 _ 代表空格,我想将它们存储在最大大小为 100 的整数数组中。我试过这个

    i=0;
    while((c=fgetc(f))!=EOF)
    {

        fscanf( f, "%d", &array[i] );
        i++;
    }

但是打印这个数组在我的屏幕上给我无限的值。

最佳答案

fgetc 从流 f 中读取下一个字符并将其作为转换为 intunsigned char 返回>。因此,您正在存储从流中读取的字符的 (ascii) 代码。

您应该使用 fscanffgetssscanf 的组合从流中读取整数,将它们读取为整数。您可以检查 fscanf 的返回值是否为 1 并继续从文件中读取。这是我的建议。

FILE *fp = fopen("input.txt", "r");
int array[100];
int i = 0, retval;

if(fp == NULL) {
    printf("error in opening file\n");
    // handle it
}

// note the null statement in the body of the loop
while(i < 100 && (retval = fscanf(fp, "%d", &array[i++])) == 1) ; 

if(i == 100) {
    // array full
}

if(retval == 0) {
    // read value not an integer. matching failure
}

if(retval == EOF) {
    // end of file reached or a read error occurred
    if(ferror(fp)) {
        // read error occurred in the stream fp
        // clear it
        clearerr(fp);
    }
}

// after being done with fp
fclose(fp);

关于c - 从以空格分隔的文件中读取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22985871/

相关文章:

c - 如何打印 C 中方程式的答案?

c - 单行中的前/后增量递减评估

php - 更改通过表单上传的 tmp 文件的文件名

java - Java套接字将byte []传输到.wav

java - 将循环中的数据保存到数组

java - 来自客户端的用户输入不会发送到服务器

c - 为什么会出现 "assigning to ' int *' from incompatible type ' void *' "错误?

c - 无法在需要整数返回类型的函数中返回 NULL

java - Java 中的错误消息帮助

c++ - 从 char 字符串 c++ 中删除新行