c++ IO操作
记录一下c++的几种IO类,方便以后写代码时查阅。
iostream 用于读写流,fstream用于读写文件,sstream用于从string类中读写数据
iostream类
常用的操作是cin和cout
#include <iostream>
using namespace std;
int main() {
int info;
cin >> info;
cout << info;
return 0;
}
fstream类
类型 | 描述 |
---|---|
ifstream | 从文件读取数据 |
ofstream | 从文件写入数据 |
fstream | 从文件读写数据 |
上述三种类型都属于fstream类,使用时需要加fstream
ifstream使用
#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使用
#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;
}