c++ fstream sstream文件读写,变量存储

这篇博客介绍了如何使用C++的fstream和sstream库进行文件的读写操作,包括从txt文件中逐行读取字符串并按空格分隔数字,以及将数据结构变量写入txt文件。示例中定义了data结构体,并展示了读取和写入文件的函数实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++ fstream sstream文件读写,变量存储

参考博客:
C++从文件中逐行读取字符串并按空格分隔数字
C++ 变量写入
C++的ofstream写文件,文件保存CSV格式
C++文件读写详解(ofstream,ifstream,fstream)

#include <iostream>
#include <vector>
#include <string>
#include <list>
#include <sstream>
#include <fstream>
#include <iomanip>
using namespace std;
 

#include "iostream"
#include<fstream>
using namespace std;

struct  data
{
   double x;
   double y;
   double z;
   double w;
}points;

/*读取txt,存储在变量data中*/
void readText(char* path){
    double data1;
    double data2;
    double data3;
    double data4;
    fstream file;
    istringstream iss;
    file.open(path);
    string s;
    while (getline(file,s)){
        iss.clear();
        iss.str(s);
        iss >> data1 >> data2 >> data3 >> data4;
        std::cout<<"data = "<<data1 << "data2 = " <<data2<< std::endl;        
    }
}

/*把变量point 写入txt*/
void writeText(char* path, data point){
    std::string filePath = path;
    std::ofstream file;
    file.open(filePath, std::ios::out);
    if(!file)
    {
        std::cout << "open csv file error " << std::endl;
        return;
    }
    for (int i; i < 10; i++){
    file << point.x << "\t" <<  point.y  << "\t" <<  point.z  << "\t" <<  point.w  << "\t"  << std::endl;
    }
    file.close(); 
}

int main(int argc, char const *argv[])
{

    points.x = 1;
    points.y = 1;
    points.z = 1;
    points.w = 1;
    writeText("text.txt", points);
    readText("text.txt");

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值