2

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

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

谁能向我解释出了什么问题?

4

3 回答 3

2

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

如果这是正确的,我们可以稍微简化代码:

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.
于 2012-04-05T08:25:04.427 回答
1

有几个问题:

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

memset()如果您担心,您应该使用清除阵列。无需清除将要被覆盖的数组,例如linefgets().

于 2012-04-05T08:20:43.400 回答
0

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

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

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

atoi(array[i])的和atoi("R 32\n")例子一样。

于 2012-04-05T08:22:22.430 回答