如何将txt文件存储为两个字符串数组?

时间:2015-10-19 00:25:27

标签: c arrays string io

现在我被困在如何从文本文件中获取字符串并根据这些单词创建两个单独的数组。文件中的字符串示例如下:

BQN Aguadilla,波多黎各

格式:

<3 letter code><2 white spaces><a string up to 100 characters>

有一个100 strings列表,我正在尝试创建一个数组来存储3个字母的代码,另一个array来存储机场。

代码:

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

    #define MAX_LINE_LENGTH 1000

    int main()
    {
      FILE *airports;
      airports = fopen("airports.txt", "r");
      FILE *routes;
      routes = fopen("routes.txt", "r");
      FILE *flights;
      flights = fopen("flights.txt", "r");

      char line[MAX_LINE_LENGTH];
      char air[100][3];
      char airp[100][100];


      if (airports == NULL)
        {
           printf("Could not open database files\n");

        }
      else
        {
          int i = 0;
          while(fgets(line, MAX_LINE_LENGTH, airports) != NULL)
            {
              sscanf(line, "%s" , air[i]);
              strcpy(airp[i], line+5);
               i++;


            }
          printf("%s" "%s", air, airp);

此项目还有更多内容,因此代码不完整。

我已经包含printf只是为了查看数组是否有效。到目前为止,它只是将所有3个字母代码打印在一行中,然后只打印第一个机场。

我的描述有点令人困惑,但任何帮助都将不胜感激!

1 个答案:

答案 0 :(得分:0)

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


#define MAX_LINE_LENGTH 100
int  getline(char ** lineptr, size_t * linelen, FILE * stream);


int main()
{
  FILE *airports;
  airports = fopen("airports.txt", "r");
  FILE *routes;
  routes = fopen("routes.txt", "r");
  FILE *flights;
  flights = fopen("flights.txt", "r");

  char line[MAX_LINE_LENGTH];

  char air[5][100];
  char airp[100][100];
    int i = 0,lines=0;

  if (airports == NULL)
    {
       printf("Could not open database files\n");
        exit(1);
    }
  else
    {


        while (fgets( line,  MAX_LINE_LENGTH, airports)  )
        {
            for(int j=0 ; j<MAX_LINE_LENGTH;j++){
                if(line[j]=='\n'){
                    line[j]=0;
                    break;
                }
            }

            sscanf(line, "%3s" , air[lines]); //first 3 chars
            strcpy(airp[lines],&line[4]);   // the remaining chars starting from 4

            lines++;

            if(lines==100) // up to 100 line allowed
                break;

        }
      fclose(airports);
    }

    // printing the arrays
    for(i=0;i<lines;i++){
        printf("%d - '%s' - '%s'\n",i+1,air[i],airp[i]);
    }


}