c++从输出文件中读取某些行
C++ reading certain lines from output file
我正在制作一个类程序,需要根据一个人选择的"数据集"从输出文件中读取某些行。例如,如果一个人输入所需数据集的"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
如果你知道一行的确切长度,你可以简单地寻找所需的位置。但从你的示例数据集来看,你似乎没有。所以你需要逐行读取文件,直到你到达所需的位置。
相关文章:
- C++试图读取一个文件并输出到另一个文本文件
- 如何使用C++读取另一个程序中的源代码输出
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 从文件读取并通过矢量输出到控制台
- 从popen()读取的输出是否在pclose()之前完成
- C++ 读取未知数量的整数到 cin 并输出总和
- libmpg123 在我使用整数编码读取 mp3 时强制浮点输出
- 尝试从 txt 文件中读取两条数据并输出它们 [C++]
- 将多个效果与 libSox 链接并读取输出数据的正确方法
- 如何从控制台启动可执行文件并使用Qt读取输出
- C#类过程 - 控制C 应用程序,不可能读取输出
- 如何运行批处理文件和读取输出
- popen 管道执行程序和读取输出的替代方法
- 读取/输出文件时出现问题
- 如何从流读取输出
- 从C/ c++编码的应用程序中读取输出流
- 如果你的程序在运行时几乎立即退出,如何确保控制台窗口保持打开状态以读取输出
- 如果未读取输出,端点将抛出无效参数
- 如何用c++打开、读取输出和输入.jar文件
- 使用 C++ 从 COM 端口读取输出数据