寫入文本文件
#include <iostream>
#include <fstream>//ofstream類需要包含的頭文件
using namespace std;void test01()
{//1、包含頭文件 fstream//2、創建流對象ofstream fout;/*3、指定打開方式:1.ios::out、ios::trunc 清除文件內容后打開2.ios::app 文件末尾追加內容*/fout.open(R"(C:\Users\18757\Desktop\pythontext\out.txt)", ios::out);//4、寫內容fout << "西施|19|極漂亮\n";fout << "冰冰|21|漂亮\n";fout << "冪冪|25|一般\n";//5、關閉文件fout.close();
}int main()
{test01();
}
讀取文本文件
#include <iostream>
#include <fstream>//ifstream類需要包含的頭文件
#include <string>
using namespace std;void test01()
{//1、包含頭文件 fstream//2、創建流對象ifstream fin;//3、打開方式只有:ios:infin.open(R"(C:\Users\18757\Desktop\pythontext\out.txt)", ios::in);//4、一行行讀取文件string buffer;/*方式一while (getline(fin,buffer)) {cout << buffer << endl;}*///方式二while (fin >> buffer) {cout << buffer << endl;}//5、關閉文件fin.close();
}int main()
{test01();
}
getline補充
getline()的原型是istream& getline ( istream &is , string &str , char delim );
char delim表示遇到這個字符停止讀入,通常系統默認該字符為’\n’,也可以自定義字符