【问题标题】:Get numbers only from a text file using c仅使用 c 从文本文件中获取数字
【发布时间】:2012-04-05 08:15:14
【问题描述】:

/已编辑/ 我是新来的。 我有一个文本文件,内容如下:

6
<cr>
R 0
R 1
R 4
R 36
R 0
R 4

这就是我所拥有的。我想将每一行读入一个数组,这样我就可以将该数组转换为一个整数,这样我以后就可以只打印我想要的那一行的数字了。

    #include <stdio.h>
    #include <conio.h>
    #include <math.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <string.h>


    int main()
    {
        FILE *fr;   /*declares file pointer*/
        int i, j, num[32];
        char array[32][32], input_file[32], line[32];
        printf("Enter file: ");
        fflush(stdin);
        scanf("%s", input_file);    
        fr = fopen(input_file, "r");
        for(i=0;i<32;i++)
            for(j=0;j<32;j++){
                array[i][j] = \'0';
            }
            for(i=0;i<32;i++){
                line[i] = '\0';
            }
        if(fr != NULL){

            while(fgets(line, sizeof(line), fr) != NULL){
                strcpy(array[i],line);
                    num[i] = atoi(array[i]);
                        i++;
                        printf("%d\n", num[i]);
            }
        }fclose(fr);
        else{
            perror(input_file);
        }
    }

我没有收到任何错误,但打印的内容不正确;这是它打印的内容:

-370086
-370086
-370086
-370086
-370086
-370086
-370086
-370086

谁能给我解释一下出了什么问题?

【问题讨论】:

  • 我没有看到array 是在哪里声明的?

标签: c arrays file


【解决方案1】:

我想我会以不同的方式处理这个问题。尽管您没有明确说明,但我将假设第一个数字告诉我们还要阅读多少行字母/数字(不包括空白行)。所以,我们想先读一遍,然后再读其余的行,忽略任何前导的非数字,只注意数字。

如果正确,我们可以稍微简化一下代码:

int num_lines;
int i;
int *numbers;

fscanf(infile, "%d", &num_lines); // read the number of lines.

numbers = malloc(sizeof(int) * num_lines); // allocate storage for that many numbers.

// read that many numbers.
for (i=0; i<num_lines; i++)
    fscanf(infile, "%*[^0123456789]%d", numbers+i);
    // the "%*[^0123456789]" ignores leading non-digits. The %d converts a number.

【讨论】:

  • 我收到一条错误消息,说“将指针 struct_iobuf 分配给指向 char 的指针”.....它不喜欢 scanf 行。我用“fr”代替了“infile”。
  • 太棒了!我还会检查 scanf 的返回值,以防有没有数字的行。
  • @Jerry Coffin 那么在此之后,数字是否存储到“数字”中?我如何得到它们以便我可以打印出来?抱歉,这对我来说是一个全新的概念。
  • @oldbutnew:是的,您可以将numbers 视为一个数组,因此您可以将它们打印出来:for (i=0; i&lt;num_lines; i++) printf("%d\n", numbers[i]); 当您完成使用它们时,您想释放内存:free(numbers);
  • @JerryCoffin 非常感谢您的帮助,杰瑞!我已经为此工作了几天。而且我很确定我昨晚尝试像这样打印数字[i]。我认为我使用的编译器有点问题。你用的是哪一个?
【解决方案2】:

有几个问题:

  1. 您从未将input_file 设置为任何值,因此您似乎在打开一个随机文件。
  2. 您在嵌套循环中重复使用了 i
  3. 您根本没有显示 array,因此无法判断它是如何声明的。
  4. 您正在增加循环索引之前使用它来打印数字,因此您总是“丢失”并在下一个(尚未写入的)插槽中打印数字。

如果您担心的话,您应该使用memset() 来清除数组。无需清除将要被覆盖的数组,例如fgets() 写入的line

【讨论】:

  • 我添加了我留下的部分。
  • 所以我应该只是将打印移动到索引增量前面,还是需要在 while 循环之外增加索引?
【解决方案3】:

假设 array 是一个 char 数组,当你这样做时:

...
strcpy(array[i],line);
num[i] = atoi(array[i]);
...

您实际上转换了整行而不是其中的integer。您应该考虑使用fscanf,或者至少在行变量中搜索整数并进行转换。

例如,atoi(array[i])atoi("R 32\n") 相同。

【讨论】:

    猜你喜欢
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    相关资源
    最近更新 更多