C/C++编程 —— 读取和保存 TXT 文本

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);
}
相关推荐
allway22 分钟前
How to Echo Multiline to a File in Bash [3 Methods]
开发语言·chrome·bash
weixin_462446233 分钟前
手把手教你用 Bash 脚本自动更新 /etc/hosts —— 自动绑定网卡 IP 与节点名
开发语言·tcp/ip·bash
一个梦醒了5 分钟前
安装git bash选项推荐
开发语言·git·bash
ct97829 分钟前
React 状态管理方案深度对比
开发语言·前端·react
ao-weilai1 小时前
C++:哈希表
c++·哈希算法·散列表
数量技术宅1 小时前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python
汉克老师1 小时前
GESP7级C++考试语法知识(二、指数函数(1、pow() 函数)
c++·指数函数·pow·gesp7级·精度误差
华如锦1 小时前
面了很多 Java转AI Agent方向,一些面试题总结
java·开发语言·人工智能·python·ai
huangdong_1 小时前
电商商品SKU图自动分类技术实现:从DOM解析到智能归档
开发语言
dog2501 小时前
网络长尾延时的重尾本质
开发语言·网络·php