如何从文本文件中的某些行开始读取

C++: how to start reading from certain lines in a txt file?

本文关键字:开始 读取 文本 文件      更新时间:2023-10-16

c++初学者项目,帮助程序从某些行开始读取。

我们有一个输入文本文件,其中包含一些客户信息:姓名、地址、两个数字,每个部分占一行。我们需要读取文件,打印出名称、地址,对数字进行一些计算,并将所有三个输出发送到输出文件。

文本文件包含3个case(9行)。

我可以读取一个案例,但是我在编写一个可以遍历三个案例的循环时遇到了麻烦。我怎样才能告诉c++,它需要从第四行开始,并做与第一个情况相同的迭代?下面是我对第一种情况所做的处理。

    getline(infile, customerName);
    getline(infile, customerAddress);
    infile >> sqFeetOfTile >> costPerSqFt;

听起来好像您实际上并不想从第4行开始阅读(跳过3行),而是想要阅读3行,然后在第4行继续。

在这种情况下,你唯一的问题是读取数字不消耗它们后面的换行符,所以当你在那之后getline时,唯一的换行符成为第一个"行",不久之后,当你试图将地址读到sqFeetOfTile时,你会遇到一个错误。

最好的方法是始终读取完整的行。
如果一行包含多个部分,则将其转换为std::istringstream并从中读取部分。
这个方法不会在流中留下任何多余的换行符,你可以从第一个记录结束的地方继续。

:

void processOneCustomer(std::istream& infile)
{
    std::string customerName;
    std::getline(infile, customerName);
    std::string customerAddress;
    std::getline(infile, customerAddress);
    std::string numbers;
    std::getline(infile, numbers);
    std::istringstream numberstream(numbers);
    float sqFeetOfTile = 0;
    int costPerSqFeet = 0;
    numbers >> sqFeetOfTile >> costPerSqFt;
    // Output customer data
    // Do calculations
}
// ...
while (inFile)
{
    processOneCustomer(inFile);
}

(当然,真正的代码应该检查错误之类的东西。)

如果您想跳过前三行,只需调用std::getline三次。