日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++文本处理_文件读写

發布時間:2025/5/22 c/c++ 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++文本处理_文件读写 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

QT在進行文本讀寫時和C++一樣,是基于文本流操作的。

QT在讀取全部文本時,相對比較便捷。使用readAll()函數,配合split()進行分隔符的拆分(例如行結束符"\n"),可將拆分結果賦值給list,然后進行后續的數據處理。

ringRoadDistList = ringRoadDistStream.readAll().split("\n",QString::SkipEmptyParts);

在C++中也可以實現類似的效果:

list<string> strList;char line[100];while (false == staEnLane2Stream.eof()){staEnLane2Stream.getline(line, sizeof(line)); //c從staEnLane2Stream按行讀取sizeof(line)個數到緩沖區line中(遇到"\n",將提前截止) strList.push_back(line);}

如果遇到換行符'\n'(第一種形式)或delim(第二種形式),則讀取終止,'\n'或delim都不會被保存進s對應的數組中。

基于文本流的輸出,兩個類似:

ofstream resultStream; resultStream.open(staEnLane3Path.c_str(), ios_base::out);if (false == resultStream.is_open()){cerr << "error: unable to open output file: " << staEnLane3Path << endl;return 2;} while (lane2Map.end() != j){cout << (*j).first << " " << (*j).second << endl;resultStream << (*j).first << " " << (*j).second << endl;++j;}

舉個栗子:

// ringRoadTime.cpp : 定義控制臺應用程序的入口點。 #include "stdafx.h" #include <string> #include <cstring> #include <cstdlib> #include <fstream> #include <iostream> #include <list> #include <map> using namespace std;int _tmain(int argc, _TCHAR* argv[]) {string rootPath = "E:/superHighway/ringRoadData/GC/GC_Entry/";string staEnLane2Name = "GC_stationEntryLane2.csv";string staEnLane3Name = "GC_stationEntryLane.csv";string staEnLane2Path = rootPath + staEnLane2Name;string staEnLane3Path = rootPath + staEnLane3Name;//ifstream staEnLane2Stream(staEnLane2Path.c_str(), ios::in); ifstream staEnLane2Stream;ofstream resultStream;//文件打開,保存數據到list,關閉文件staEnLane2Stream.open(staEnLane2Path.c_str(), ios_base::in);if (false == staEnLane2Stream.is_open()){cerr << "error: unable to open input file: " << staEnLane2Path << endl;return 1;}list<string> strList;char line[100];while (false == staEnLane2Stream.eof()){staEnLane2Stream.getline(line, sizeof(line));strList.push_back(line);}staEnLane2Stream.close();resultStream.open(staEnLane3Path.c_str(), ios_base::out);if (false == resultStream.is_open()){cerr << "error: unable to open output file: " << staEnLane3Path << endl;return 2;}//數據插入map中,進行匹配map<string, string> lane2Map;list<string>::iterator k = strList.begin();for (; k != strList.end(); ++k){size_t i = (*k).find_first_of(",");lane2Map.insert(pair<string, string>((*k).substr(0,i), (*k).substr(i+1)));}map<string, string>::iterator j = lane2Map.begin();while (lane2Map.end() != j){cout << (*j).first << " " << (*j).second << endl;resultStream << (*j).first << " " << (*j).second << endl; //基于文本流的數據寫入++j;}resultStream.close();system("pause");return 0; }

?

轉載于:https://www.cnblogs.com/Lunais/p/6073182.html

總結

以上是生活随笔為你收集整理的C++文本处理_文件读写的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。