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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/111306.html
標籤:其他
