0

我不是C天才。所以..首先对我的愚蠢问题感到抱歉。我有一个 .txt 文件或 .dta(随便),我想用 C 语言读取它。我想获取 txt 的数字,格式化为两列和 x 行,并将所有数据存储到一个矩阵中(或向量)。

据了解,我正在使用此代码:

/*
** File FILE_3.C
**
** Illustrates how to read from a file.
**
** The file is opened for reading.  Each line is successively fetched
** using fgets command.  The string is then converted to a long integer.
**
** Note that fgets returns NULL when there are no more lines in the file.
**
** In this example file ELAPSED.DTA consists of various elapsed times in
** seconds.  This may have been the result of logging the time  of events
** using an elapsed time counter which increments each second from the
** time the data logger was placed in service.
**
** Typical data in elapsed.dta might be;
**
** 653 75
** 142 90
** 104 10
** 604 10
** 124 12
**
*/

#include <stdio.h>   /* required for file operations */
FILE *fr;            /* declare the file pointer */

main()

{
   int n;
   long elapsed_seconds;
   char line[80];


   fr = fopen ("elapsed.txt", "rt");  /* open the file for reading */
   /* elapsed.dta is the name of the file */
   /* "rt" means open the file for reading text */

   while(fgets(line, 80, fr) != NULL)
   {

 sscanf (line, "%ld", &elapsed_seconds);
 /* convert the string to a long int */
 printf ("%ld\n", elapsed_seconds);
   }
   fclose(fr);  /* close the file prior to exiting the routine */
} /*of main*/

你能帮助我吗?

感谢您的回答

4

2 回答 2

1

您可以使用 fscanf 而不是 fgets 和 sscanf。并仔细查看 scanf 格式(http://en.wikipedia.org/wiki/Scanf_format_string

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

int main()
{
    FILE * fr;  
    int row = 0;
    int i;
    int arr[8][2]; // max 8 rows!

    fr = fopen ("file.txt", "r");
    if ( fr == NULL )
    {
        printf( "Can't open file\n" );
        exit(0);
    }

    while( fscanf (fr, "%d %d\n", &arr[row][0], &arr[row][1]) == 2 )
        row ++;

    for (i = 0; i < row; i++)
        printf( "(%d) (%d)\n", arr[i][0], arr[i][1] );

    fclose(fr);
} 
于 2013-06-16T09:03:23.150 回答
0

您必须分配一个数组来保存您的 elapsed_second 值。

 long * seconds_array;
 seconds_array = calloc( SIZEOFARRAY, sizeof(long));

在 c 中,数组或多或少与指针相同。

就像在这个例子中来自http://www.cplusplus.com/reference/cstdlib/calloc/

在示例中,pData 具有固定大小,这意味着您必须事先知道您有多少个数字,或者您必须跟踪输入的数字数量,并在空间不足时分配一个新的 pData 数组。

在示例中,数字取自标准输入,但原理相同。从文件中读取时。在您的情况下,for 循环可能更像是一个 while 循环。

/* calloc example */
#include <stdio.h>      /* printf, scanf, NULL */
#include <stdlib.h>     /* calloc, exit, free */

int main ()
{
  int i,n;
  int * pData;
  printf ("Amount of numbers to be entered: ");
  scanf ("%d",&i);
  pData = (int*) calloc (i,sizeof(int));
  if (pData==NULL) exit (1);
  for (n=0;n<i;n++)
  {
    printf ("Enter number #%d: ",n+1);
    scanf ("%d",&pData[n]);
  }
  printf ("You have entered: ");
  for (n=0;n<i;n++) printf ("%d ",pData[n]);
  free (pData);
  return 0;
}

PS当你完成它时不要忘记在你的阵列上调用免费。 http://www.cplusplus.com/reference/cstdlib/free/

于 2013-06-16T08:59:04.303 回答