C语言 从文本文件中读取并存储在二维数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18942719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:31:29  来源:igfitidea点击:

Reading from a text file and storing in a 2D array

c

提问by Butterflay

I've been trying to store a matrix input in a txt file in a array but it show me this: this is the code

我一直在尝试将矩阵输入存储在一个数组中的 txt 文件中,但它向我展示了这一点:这是代码

   #include <stdio.h>

int main()
{
    int c, i, j, row, col, nl, cr;

    row = col = nl = cr = 0;

    FILE *fp = fopen("g.txt", "r");

    // Figure out how many rows and columns the text file has
    while ((c = getc(fp)) != EOF)
    {
        if (c == '\n')
            nl++;
        if (c == '\r')
            cr++;

        col++;

        if (c == '\n')
            row++;

       putchar(c);
    }

    col = (col - (nl + cr));
    col = (int) (col/row);

   // printf("\nnumber of rows is %d\n", row);


    // read letters into array

    char array[row][col];

    if ( fp )
       {
        for ( ;; )
              {
            c = getc(fp);
                 if ( c == EOF )
                 {
                        break;
                 }
                 if ( c != '\n' && c != '\r' )
                 {
                        array[i][j] = c;

                    if ( ++j >= col )
                        {
                            j = 0;
                            if ( ++i >= row )
                            {
                                break;
                            }
                        }
                }
            }
        fclose(fp);
    }

    for ( i = 0; i < row; i++ )
    {
            for ( j = 0; j < col; j++ )
            {
                 putchar( array[i][j]);
            }
            putchar('\n');
    }
    return 0;
}

somone have any idea please? exemple of the txt file :

有人知道吗?txt 文件示例:

255  50  9  50  1  50  50  1
50  255  50  50  50  50  50 50
50  50  255  50  50  50 50  50
8  50  50  255  50 50  50  50
50  50  50  50 255 50  50  50
50  50  50 50  50  255  50  50
1  50 50  50  50  50  255  50
2 50  50  50  50  50  50  255 

my program show me this:

我的程序向我展示了这个:

255 50   9   50  1   50   50   1
50  255  50  50  50  50   50   50
50  50   255 50  50  50   50   50
8   50   50  255 50  50   50   50
50  50   50  50  255 50   50   50
50  50   50  50  50  255  50   50
1   50   50  50  50  50   255  50
2   50   50  50  50  50   50   255     $■( 1gíuát09■????¤?u"òávD   ê$[
?  e2(     ?       l    ?      ■???
  ê$[ ?   l       -2( O??v[ 4■( Q?á
v?   #?áv┬2║O?|?v    ?|?ve┬ív
 ■(     x■( ?|?v ó2?????@■(  á?v╚♀[ L
■( wˉ?v?   ê■( I┴áv?|?v↓┴áv~2║O
   ó2?????\■( ■???─?( e┬íví┬29??

for the input file it show the good one ,but the problem is for the array output i don't undrestand why it show me this caracters

对于输入文件,它显示了良好的文件,但问题在于数组输出,我不明白为什么它会向我显示这个字符

回答by Filipe Gon?alves

You never change j, it always remains 0, so you're writing every position a[i][0]. atoi(line); will convert the first number in the line only. That's why your program is only storing the first column.

你永远不会改变 j,它总是保持为 0,所以你正在写每个位置 a[i][0]。atoi(线);将只转换行中的第一个数字。这就是为什么你的程序只存储第一列。

A possible approach to fix this would be something like:

解决此问题的可能方法是:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int  i=0,totalNums,totalNum,j=0;
    size_t count;
    int numbers[100][100];
    char *line = malloc(100);

    FILE *file;  /* declare a FILE pointer  */
    file = fopen("g.txt", "r");  /* open a text file for reading */

    while(getline(&line, &count, file)!=-1) {
        for (; count > 0; count--, j++)
            sscanf(line, "%d", &numbers[i][j]);
        i++;
    }

    totalNums = i;
    totalNum = j;
    for (i=0 ; i<totalNums ; i++) {
      for (j=0 ; j<totalNum ; j++) {
        printf("\n%d",  numbers[i][j]);
      }
    }
    fclose(file);
    return 0;
}

That code will read the entire line, and then parse it number by number until no more numbers are there.

该代码将读取整行,然后逐个解析它,直到没有更多数字为止。

I didn't really understand if input is supposed to be integers or doubles, note that you declare a 2D array of doubles but then you call atoi(). The code I posted assumes it's integers, but then make sure to change your array to a 2D array of ints (or if they really are doubles, change the format string in sscanf).

我真的不明白输入应该是整数还是双精度数,请注意,您声明了一个双精度数的二维数组,然后调用了 atoi()。我发布的代码假定它是整数,但请确保将数组更改为整数的二维数组(或者如果它们确实是双精度数,请更改 sscanf 中的格式字符串)。

回答by user1502952

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main(void)
{
  FILE * fp;
  char * line = NULL;
  size_t len = 0;
  ssize_t read;

  const char *s = " ";
  char *token = NULL;

  int i = 0;
  double arr[200];
  int j;

  fp = fopen("g.txt", "r");
  if (fp == NULL)
  {
    printf("Error opening");
    exit(EXIT_FAILURE);
  }

  while ((read=getline(&line, &len, fp)) != -1)
  {
     token = strtok(line, s);

     while(token != NULL)
     {
       arr[i] = atoi(token);
       printf("%f\n", arr[i]);
       token=strtok(NULL,s);
       i++;
     }
  }

  exit(EXIT_SUCCESS);
  return 0;
}

getlinewill read file line by line and strtokwill split entries based on space and will store seperately entries in array. Also single dimensional array is enough to store values.

getline将逐行读取文件,并strtok根据空间拆分条目,并将条目单独存储在数组中。一维数组也足以存储值。