c++从输出文件中读取某些行

C++ reading certain lines from output file

本文关键字:读取 输出 文件 c++      更新时间:2023-10-16

我正在制作一个类程序,需要根据一个人选择的"数据集"从输出文件中读取某些行。例如,如果一个人输入所需数据集的"1",我需要它使用数据文件的第1行到第8行(包括第8行)。如果他们为所需的数据集输入"2",我需要程序使用数据文件中的第9行到第16行(包括),如果输入"3",则使用第17行到第24行(包括)。下面是目前为止的代码-

int main()
{
    int latA, latB, latC, latD;
    int longA, longB, longC, longD;
    int AtoB, BtoC, CtoD, threeFlightTotal, nonStop;
    int dataSet;
    string cityA, cityB, cityC, cityD;
    intro();
    cout << "Which data set do you wish to use? 1, 2, or 3?  ";
    cin >> dataSet;
    while(dataSet < 1 || dataSet > 3)
    {
        cout << "Sorry, that is not a valid choice. Please choose again." << endl;
        cin >> dataSet;
    }
    ifstream dataIn;
    dataIn.open("cities.txt");
    if (dataIn.fail())
    {
        cout << "File does not exist " << endl;
        system("pause");
        exit(1);
    }
    else
    {
        cout << "File opened successfully" << endl;
    }
    dataIn.close();
    system("pause");
    return 0;
}

这是我的数据文件-

43.65 79.4      
Toronto
40.75 74
New York
33.64 84.43
Atlanta
51.5 0
London
37.78 122.42
San Francisco
47.61 122.33
Seattle
44.88 93.22
Minneapolis
41.88 87.63
Chicago
21.19 157.5
Honolulu
45.31 122.41
Portland
42.2 83.03
Detroit
25.47 80.13
Miami

我该怎么做呢?我看过其他的帖子,但我很难理解如何实施他们的解决方案。提前感谢您的帮助。

您可以直接跳过不需要的行:

//here you calculate the amount of lines to skip.
//if dataSet=1 --> linesToSkip=0, if dataSet=2 --> linesToSkip=8...
int linesToSkipt = (dataSet-1) * 8;
//getline Needs a string to load the Content.
//So we don't use the data but wee Need to store it somewhere
std::string helper;
//We use a for Loop to skip the desired amount of lines
for(int i = 0; i < linesToSkip; ++i)
    std::getline(dataIn, helper);     //Skip the unneeded lines

如果你知道一行的确切长度,你可以简单地寻找所需的位置。但从你的示例数据集来看,你似乎没有。所以你需要逐行读取文件,直到你到达所需的位置。