如何将文本文件中的不同行保存到不同数据类型的不同变量中;所有这些变量组成一个结构(在我的示例中是一个包含以下内容的flight结构)。

struct Flight
{
     int flightNum;
     char desination[30];
     char departDay[15];
};

我想通过文本文件添加的信息示例如下。
111
NYC
Monday

很明显我想把单词NYC和Monday保存为char数组,但是我想把111保存为整型变量
到目前为止
while (fscanf(flightInfo, "%s", tempName) != EOF)
{
     fscanf(flightInfo, "%d\n", &tempNum);
     flight.flightNumber = tempNum;
     fscanf(flightInfo, "%s\n", tempName);
     strcpy(flight.desination, tempName);
     fscanf(flightInfo, "%s\n", tempName)
     strcpy(flight.departDay, tempName);
}

假设flightInfo是指向文件名的指针,tempNum是整数,tempName是字符数组

最佳答案

听起来你走对了。
像这样的事情呢:

#define MAX_FLIGHTS 100
...
struct Flight flights[MAX_FLIGHTS ];
int n_flights = 0;
...
while (!feof(fp) && (n_flights < MAX_FLIGHTS-1))
{
     if (fscanf(fp, "%d\n", &flights[n_flights].flightNum) != 1)
        error_handler();
     if (fscanf(fp, "%29s\n", flights[n_flights].destination) != 1)
        error_handler();
     if (fscanf(fp, "%14s\n", flights[n_flights].departDay) != 1)
        error_handler();
     ++n_flights;
}
...

附录:
根据Chux的建议,我修改了代码,将scanf max string length设置为29(小于char[30]缓冲区大小的1),以减少潜在的缓冲区溢出。
下面是更详细的解释:
SonarSource: "scanf()" and "fscanf()" format strings should specify a field width for the "%s" string placeholder

10-08 03:12