gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:09:38 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com