gpt4 book ai didi

c - 用 C 读取文本文件,跳过第一行

转载 作者:行者123 更新时间:2023-11-30 19:44:27 25 4
gpt4 key购买 nike

我的程序有一个大问题。我想跳过从第一行开始阅读,然后开始阅读其他行。我浪费了很多时间在互联网上搜索它。

这是我的txt文件。

LP bfdhfgd ffhf  fhfhf hgf hgf hgf ffryt f uu  
1 2015-01-17 20:08:07.994 53.299427 15.906657 78.2 0
2 2015-01-17 20:09:13.042 53.299828 15.907082 73.3 11.2375183105
3 2015-01-17 20:09:22.037 53.300032 15.90741 71.2 12.2293367386
4 2015-01-17 20:09:29.035 53.300175 15.907675 71.5 10.8933238983
5 2015-01-17 20:09:38.003 53.30025 15.907783 71.4 12.3585834503
6 2015-01-17 20:09:49.999 53.300768 15.908423 72.4 14.1556844711
7 2015-01-17 20:09:58.999 53.300998 15.908652 73.7 11.2634601593
8 2015-01-17 20:10:06.998 53.301178 15.908855 72.6 10.8233728409
9 2015-01-17 20:10:15.999 53.301258 15.908952 72.3 10.3842124939
10 2015-01-17 20:10:22.999 53.301332 15.90957 71.5 10.7830705643

   void OK(char * name)
{
GPS nr1; //my structure
FILE *file;
file = fopen(name, "r+t");

if (file!=NULL)
{
cout << endl;
while (!feof(file))
{
fscanf(plik, "%d %s %d:%d:%f %f %f %f %f", &nr1.LP, &nr1.Date, &nr1.hour, &nr1.min, &nr1.sek, &nr1.dl, &nr1.sz, &nr1.high, &nr1.speed);
base.push_back(nr1);

cout << nr1.LP << " " << nr1.Date << " " << nr1.hour << ":" << nr1.min << ":" << nr1.sek << " " << nr1.dl << " " << nr1.sz<< " " << nr1.high << " " << nr1.speed <<endl;
}
}
else
{
cout << endl << "ERROR!";
exit(-1);
}

fclose(file);

}

最佳答案

首先,您的代码有点奇怪,因为您将 C++ 输出与 C 输入混合在一起。您可能想稍后修复该问题。

获得您想要的行为的方法是使用 fgets读取行(并跳过第一行),然后使用 sscanf提取值。

#include <stdio.h>


void OK(char * name)
{
GPS nr1; //my structure
FILE *file;
file = fopen(name, "r");

char buffer[1024];
memset(buffer, 0, 1024);

if (file!=NULL)
{
cout << endl;
// skip first line
fgets(buffer, 1024, file);
while (!feof(file))
{
// Read a line and parse it.
fgets(buffer, 1024, file);
sscanf(buffer, "%d %s %d:%d:%f %f %f %f %f", &nr1.LP, &nr1.Date, &nr1.hour, &nr1.min, &nr1.sek, &nr1.dl, &nr1.sz, &nr1.high, &nr1.speed);
cout << nr1.LP << " " << nr1.Date << " " << nr1.hour << ":" << nr1.min << ":" << nr1.sek << " " << nr1.dl << " " << nr1.sz<< " " << nr1.high << " " << nr1.speed <<endl;
}
}
else
{
cout << endl << "ERROR!";
exit(-1);
}

fclose(file);

}

关于c - 用 C 读取文本文件,跳过第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28142540/

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