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;
}