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

标签 c arrays string io

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

BQN 阿瓜迪亚,波多黎各

格式:

<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 个字母代码,后跟第一个机场。

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

最佳答案

#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]);
    }


}

关于c - 如何将 txt 文件存储为两个字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33204830/

相关文章:

arrays - 算法 - 检查字符串数组中的任何字符串是否是同一数组中任何其他字符串的前缀

c - 回调函数的可变参数

python - 如何屏蔽索引小于某个值的数组

arrays - 将 setState 用于数组时的无限循环

java - 如何将文本添加到 textArea 而不是替换它

regex - Powershell:使用 -replace 与正则表达式

c - getopt_long 保留可选参数的默认值

c - 从文件中读取矩阵的行和列

c++ - 验证整数中的值...?

c - 数组声明为 int v[100] 但 &(v[100]) 没有给出警告