cpp
#include <fstream>
#include <sstream>
#include <iostream>
void read_txt_with_blank_space(std::string path, std::vector<float> &elements)
{
std::ifstream infile(path);
if (infile.good()) // good()成员函数来判断当前流是否正常,判断是否到文件末尾
{
std::string line;
// 每次获取一整行,存放到line
while(getline(infile, line))
{
std::stringstream data(line);
float n1, n2, n3;
std::cout << "line: " << line << std::endl;
if(data >> n1 >> n2 >> n3) // 将当前行的数据赋给定义的变量(n1,n2,n3)
{
std::cout<< "elem: " << n1 << " " << n2 << " " << n3 << std::endl;
// 根据实际的任务需求,决定如何处理数据,这里仅仅是把数据传出去
elements.push_back(n1);
elements.push_back(n2);
elements.push_back(n3);
// 根据实际的任务需求,决定如何处理数据,这里仅仅是把数据传出去
}
}
infile.close();
}
}
void save_txt_with_blank_space(std::vector<float> elements)
{
std::ofstream f_box;
f_box.open("Demo_ReWrite.txt",std::ios::out|std::ios::app);
for (int i=0; i<elements.size(); i=i+3)
{
float n1=elements[i];
float n2=elements[i+1];
float n3=elements[i+2];
f_box << n1<< " " << n2<< " " << n3 << std::endl;
}
f_box.close();
}
void read_txt_with_comma(std::string path, std::vector<float> &nums)
{
std::ifstream file(txt_path); // 打开文件
std::string line;
std::vector<float> nums;
while(getline(file, line)) { // 逐行读取文件
std::istringstream iss(line);
std::string num_str;
while(getline(iss, num_str, ',')) { // 逐个读取以逗号隔开的浮点数
float num;
std::istringstream(num_str) >> num; // 元素以浮点数存于num变量
nums.push_back(num); // 存储到vector中
}
}
}
int main()
{
// 1. 读取以【空格】隔开的文本,并保存
std::string path="demo.txt";
/* demo.txt 内容如下
3 0.31865 -2.43505
2 0.558651 -5.43505
*/
std::vector<float> elements1;
read_txt_with_blank_space(path,elements1);
save_txt_with_blank_space(elements1);
// 2. 读取以【逗号】隔开的文本,并保存
std::string path="demo1.txt";
/* demo1.txt 文本内容如下
0, 1, 0.31865, -2.43505
2, 1, 0.558651, -5.43505
*/
std::vector<float> elements2;
read_txt_with_comma(path,elements2);
}