栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++保存txt文件实现方法代码实例

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++保存txt文件实现方法代码实例

简单示例

#include 
#include 
#include 
#include 
using namespace std;
 
int main()
{
  ifstream myfile("in.txt");
  ofstream outfile("out.txt", ios::app); //ios::app指追加写入
  string temp;
   
  while (getline(myfile, temp)) //按行读取字符串
  {
    outfile << temp<

实际应用

一个det.txt存的都是目标检测的信息

1TXT数据存放数据格式

1,-1,281.931,187.466,79.93,209.537,0.997784,-1,-1,-1
1,-1,56.6878,144.225,93.5572,295.907,0.997601,-1,-1,-1
1,-1,378.618,188.922,166.431,234.127,0.995973,-1,-1,-1
1,-1,203.983,207.153,45.553,133.834,0.985409,-1,-1,-1

(抽取单个目标展示)

帧号 目标ID x y w h 准确度

1,-1,291.557,192.468,39.494,119.227,0.995128,-1,-1,-1

(虽然看起来很乱,而且没有换行,但是程序按照行读取还是能分开??? )

程序功能:

1 读取原txt

2 存到另一个txt里面

3 解析其中的数据

这里的解析没有用到字符串分割等,而是利用了istringstream对象直接将不同类型的数据导给不同的变量。

istringstream对象解析的简单示例

#include 
#include 
 
using namespace std;
 
int main()
{
  istringstream istr;
  istr.str("1 56.7");
  //上述两个过程可以简单写成 istringstream istr("1 56.7");
  cout << istr.str() << endl;
  int a;
  float b;
  istr >> a;
  cout << a << endl;
  istr >> b;
  cout << b << endl;
  return 0;
}

  上例中,构造字符串流的时候,空格会成为字符串参数的内部分界,例子中对a,b对象的输入"赋值"操作证明了这一点,字符串的空格成为了整型数据与浮点型数据的分解点,利用分界获取的方法我们事实上完成了字符串到整型对象与浮点型对象的拆分转换过程。

工程代码:

#include 
#include 
#include 
#include 
 
#include "opencv2/video/tracking.hpp"
#include "opencv2/highgui/highgui.hpp"
 
using namespace std;
using namespace cv;
 
typedef struct TrackingBox
{
  int frame;
  int id;
  Rect_ box;
}TrackingBox;
 
 
 
 

void TXTtoBOX() {
  string inFileName = "det.txt";
  string outFileName = "out.txt";
 
  ifstream myfile(inFileName);
  ofstream outfile(outFileName, ios::app); //ios::app指追加写入
 
 
  if (!myfile.is_open())
  {
    cerr << "Error: can not find file " << inFileName << endl;
    return;
  }
  if (!outfile.is_open())
  {
    cerr << "Error: can not find file " << outFileName << endl;
    return;
  }
 
  string detLine;//存放读取出的单个目标信息
  istringstream ss;
  vector detData;
  char ch;//存放逗号,没有实际用处,去除数据间的逗号
  float tpx, tpy, tpw, tph;
 
  while (getline(myfile, detLine)) //按行读取字符串
  {
    TrackingBox tb;
    ss.str(detLine);
    ss >> tb.frame >> ch >> tb.id >> ch;// ch用来存放逗号
    ss >> tpx >> ch >> tpy >> ch >> tpw >> ch >> tph;
    ss.str("");//清空后面不管
 
    tb.box = Rect_(Point_(tpx, tpy), Point_(tpx + tpw, tpy + tph));
    detData.push_back(tb);
 
    outfile << detLine << endl;//写文件
    cout <<"detLine:"<< detLine << endl;
    cout << "x:"<

运行之后

重新按行存放输出到out.txt

解析

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/61247.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号