c++ IO operation

c++ IO operation

记录一下c++的几种IO类,方便以后写代码时查阅。
iostream 用于读写流,fstream用于读写文件,sstream用于从string类中读写数据

iostream class

常用的操作是cin和cout
#include <iostream>

using namespace std;

int main() {
    
    

	int info;
	cin >> info;
	cout << info;
	return 0;
}

fstream class

Types of description
ifstream Read data from file
ofstream Write data from file
fstream Read and write data from files

The above three types belong to the fstream class, and fstream needs to be added when used

ifstream use

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

/*
	按照空格读取每一段数据
*/
void ReadDataBySpace(const char * file) {
    
    
	ifstream rd(file);
	string s;
	while (rd >> s) {
    
    
		cout << "info:" << s << endl;
	}
	
}

/*
	按照行读取每一段数据
*/

void ReadDataByLine(const char* file) {
    
    
	ifstream rd(file);
	char s[1024];
	while (rd.getline(s,1024)) {
    
    
		cout << "info:" << s << endl;
	}
}

int main() {
    
    
	string file = "text.txt";
	ReadDataBySpace(file.c_str());
	ReadDataByLine(file.c_str());
	return 0;
}

ofstream use

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


int main() {
    
    
	string wfile = "write.txt";
	string rfile = "text.txt";
	ofstream out(wfile.c_str());
	ifstream in(rfile.c_str());
	if (!out.is_open()) {
    
    
		cout << "open write.txt failed" << endl;
	}
	if (!in.is_open()) {
    
    
		cout << "open text.txt failed " << endl;
	}
	char s[1024] = {
    
    0};
	while (in.getline(s,1024)) {
    
    
		out << s << endl;;
	}
	in.close();
	out.close();

	return 0;
}

sstream

一般用于类型转换
#include <iostream>
#include <sstream>
#include <string>

using namespace std;


int main() {
    
    
	stringstream ss;
	string info = "1234";
//	int x = 0;
//	ss << info;
//	ss >> x;
//	cout << "x:" << x << endl;
	int m = 9999;
	ss << m;
	ss >> info;
	cout << "info:" << info << endl;


	return 0;
}

Guess you like

Origin blog.csdn.net/clearwwu/article/details/108733324