c++使用fstream查找特定的数据
C++ using fstream to find a specific data
我是c++新手,需要fstream方面的帮助。我已经搜索和阅读了,但找不到这个信息。
我想从文本文件中的特定行获取数据。
例如,在txt文件中,我有:
10行11列,每列可以是int、char、string等
无论如何我可以检索一个变量从一个特定的行和列,而不使用数组?
示例:如果我想从第9行和第4列检索变量。
提前感谢!
如果您确切地知道每行的长度以及每行中每列的位置,您可以准确地计算出您要去的位置并使用seekg
来定位自己。
对于以文本形式存储的数据,这是不常见的。你通常需要编写一个函数来完成以下工作:
- 打开文件
- 在文件上使用
std::getline
N次,从文件到达第N行。 - 将该行写入
std::stringstream
。 - 在
std::stringstream
上使用>>
M次将列读入std::string
。 - 将第m列从
std::string
转换为相应的数据类型。 - 返回转换后的第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;
}
}
//---
相关文章:
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 在C++中查找像素 RGB 数据的最快方法是什么?
- 一种有效的数据结构,用于按 ID 访问和查找加权随机项
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 用于添加和查找查询的适当数据结构
- 如何在数据文件中查找和显示内容
- 用于查找元素的数据结构
- C++ 数据结构队列:使用 for 循环查找队列中最大的元素
- GLSL 计算着色器 使用查找表设置缓冲区会导致不写入任何数据,与其他数据设置相同的缓冲区有效
- 查找索引数据结构,例如`sTD :: vector`(非数组)
- 使用STD :: MAP在数据及其性能问题中查找重复项.我可以预先分配吗?
- 在数据类型类的列表中查找 elem
- C++ 查找流数据的最大值
- 使用算法标头查找自定义数据类型的minmax
- 是否有具有对数时间插入、删除和查找(带距离)的排序数据结构
- 用于在具有更新查询的二维矩阵中查找最大值的最佳数据结构
- 如何使用C++查找数据集中的局部最大值
- 从 txt 文件中查找和打印数据
- 具有非常快速的内>数据查找和快速反向查找(搜索/插入/删除数据)的压缩字典?