1. 程式人生 > 程式設計 >C++儲存txt檔案實現方法程式碼例項

C++儲存txt檔案實現方法程式碼例項

簡單示例

#include <windows.h>
#include <fstream>
#include <iostream>
#include <string>
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<<endl;//寫檔案
   
  }
  myfile.close();
  outfile.close();
  while (1);
  return 0;
}

實際應用

一個det.txt存的都是目標檢測的資訊

1TXT資料存放資料格式

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

(抽取單個目標展示)

幀號 目標ID x y w h 準確度

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

C++儲存txt檔案實現方法程式碼例項

(雖然看起來很亂,而且沒有換行,但是程式按照行讀取還是能分開??? )

C++儲存txt檔案實現方法程式碼例項

程式功能:

1 讀取原txt

2 存到另一個txt裡面

3 解析其中的資料

這裡的解析沒有用到字串分割等,而是利用了istringstream物件直接將不同型別的資料導給不同的變數。

istringstream物件解析的簡單示例

#include <iostream>
#include <sstream>
 
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 <windows.h>
#include <fstream>
#include <iostream>
#include <string>
 
#include "opencv2/video/tracking.hpp"
#include "opencv2/highgui/highgui.hpp"
 
using namespace std;
using namespace cv;
 
typedef struct TrackingBox
{
  int frame;
  int id;
  Rect_<float> box;
}TrackingBox;
 
 
 
 
/*
1TXT資料存放資料格式
1,-1
1,-1
(抽取單個目標展示)
幀號 目標ID x y w h 準確度
1,-1,-1,-1
 
*/
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<TrackingBox> 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_<float>(Point_<float>(tpx,tpy),Point_<float>(tpx + tpw,tpy + tph));
    detData.push_back(tb);
 
    outfile << detLine << endl;//寫檔案
    cout <<"detLine:"<< detLine << endl;
    cout << "x:"<<tpx << "  y:"<< tpy << " w:" << tpw << " h:" << tph <<endl;
 
  }
  myfile.close();
  outfile.close();
  while (1);
 
 
}
int main()
{
  TXTtoBOX();
   
  return 0;
}

執行之後

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

C++儲存txt檔案實現方法程式碼例項

解析

C++儲存txt檔案實現方法程式碼例項

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。