有没有办法从.txt文件中读取一行特定的信息?

问题描述

对于c ++来说,我是新手,我有一个目前正在学校里做的项目,但是我一直坚持如何从用户输入选择中获取整行信息。

这是我的txt文件的样子

1 Home Work 5
2 Work Home 5
3 Home School 6
4 School Home 6
5 Work School 8
6 School Work 8

所以基本上,如果他们输入/ cin选项3,但是我如何打印并获取第3行中的值以供以后显示和计算?

这是我的代码

#include <iostream>
#include <iomanip>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <cstdlib>
#include <Windows.h>
#include <cmath>

void bookingmenu();
void confirmedbooking(double calc);

double calc;
using namespace std;

int main()
{

    ifstream inFile;
    string PUP,Dropoff,others,otherstwo;
    double distance = 0,calc;
    string ON;
    int sel;
    char choice;

    inFile.open("blist.txt");

    if (!inFile)
        cout << "Error,unable to open text file.\n" << endl;

    else
        cout << left << fixed << setprecision(2);//how many dp
    cout << left << setw(25) << "Option Number" << left << setw(25) << "Pick Up Point" << "Dropoff Point" << endl; //display column header

    while (!inFile.eof())
    {
        inFile >> ON >> PUP >> Dropoff;
        if (inFile.fail()) break;
        cout << left << setw(25) << ON << left << setw(25) << PUP << Dropoff << endl;

    }

    cout << "Please select an option for your trip: ";
    cin >> sel;
    
    //(im stuck after here)
    
    cout << "You have selection option number " << ON << " and your pickup point is " << PUP << " and your dropoff point is " << Dropoff << endl;


    system("pause");
    return 0;

}

解决方法

列出您需要做的事情:

  1. 读取文件(即将完成)
  2. 打印文件中的选项(完成)
  3. 将数据放在我们可以稍后查找的位置(未完成)
  4. 从用户那里获得选项(完成)
  5. 查找选项(未完成)
  6. 打印所选选项(几乎完成)

固定点1

当前代码从数据行中读取三个字段。有4个字段。需要从流中删除第四个字段。

int unused;
while (inFile >> ON >> PUP >> Dropoff >> unused) // read unused field into junk variable
{
    //print
}

实施点3

定义一个可以存储数据的结构

struct record
{
    string PUP;
    string Dropoff;
};

选项号可能会用作查找结构的关键字,因此它不必在结构中。

接下来,我们需要一个container来存储这些记录

如果保证文件以可预测的选项号开头并以连续的顺序列出,则可以使用std::vector来存储record。如果列表是可预测的,顺序排列的并且大小已知,则可以使用std::array。如果不是,请使用关联表将选项号映射到record。我们没有任何订购或尺寸保证,因此我将以std::map

进行演示
record in;
map<int,record> records; // convenient data structure for look-up
int ON;
int unused; // need to read and dum that last field on the line
while (inFile >> ON >> in.PUP >> in.Dropoff >> unused)
{
    records[ON] = in; // store row in datastructure at the option number.
}

如果您很聪明,则将读取文件并同时打印菜单。否则,您将读取文件两次,或者不必要地循环遍历record的容器。

实施点5

在容器中查找记录。如果使用std::map,那可以很简单

record & out  = records.at(sel);
如果选项不在列表中,则

at将引发异常。您可以捕获并处理异常,也可以让程序崩溃。

固定点6

我们使用对record的引用来更新现有代码,以使用正确的record