c++使用fstream查找特定的数据

C++ using fstream to find a specific data

本文关键字:数据 查找 使用 fstream c++      更新时间:2023-10-16

我是c++新手,需要fstream方面的帮助。我已经搜索和阅读了,但找不到这个信息。

我想从文本文件中的特定行获取数据。

例如,在txt文件中,我有:

10行11列,每列可以是int、char、string等

无论如何我可以检索一个变量从一个特定的行和列,而不使用数组?

示例:如果我想从第9行和第4列检索变量。

提前感谢!

如果您确切地知道每行的长度以及每行中每列的位置,您可以准确地计算出您要去的位置并使用seekg来定位自己。

对于以文本形式存储的数据,这是不常见的。你通常需要编写一个函数来完成以下工作:

    打开文件
  1. 在文件上使用std::getline N次,从文件到达第N行。
  2. 将该行写入std::stringstream
  3. std::stringstream上使用>> M次将列读入std::string
  4. 将第m列从std::string转换为相应的数据类型。
  5. 返回转换后的第m列。
//-------------------------------
//--This code maybe can help you
//-------------------------------
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
int main ()
{
    char lBuffer[100];
    //---
    std::string myfilename = "/var/log/mylog.log";
    std::ifstream log_file ( myfilename );
    std::stringstream my_ss;
    std::string c1, c2, c3;
    //---
    std::cout << "Rec1tt Rec2tt Rec3" << std::endl;
    while ( ! log_file.eof() )
    {
            log_file.getline(lBuffer,80);
            my_ss << lBuffer;
            my_ss >> c1;
            my_ss >> c2;
            my_ss >> c3;
            std::cout << c1 << "tt " << c2 << "tt "   << c3 << std::endl;
    }
}
//---