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

这是我的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);

}

08-27 11:59