C++中文件讀取處理(按行或者單詞)

前段時間參加藍橋杯,遇到一些題目,題目本身不難,按照常規思路寫代碼即可,但是我忘了如何讀取文件了。。。面對一堆數據楞是寫不出。還有幾天是藍橋杯的決賽,所以爲了避免踩同樣的坑,我打算通過實例複習下文件讀寫。


文件讀寫需要引fstream,如果對fstream不瞭解的話,可以查一查官方的文檔cplusplus這個網站。

這裏寫圖片描述

一般常用的函數就是open,close,getline…具體的函數不會了直接查一下,學會用官方文檔。我主要想通過實例來學習使用這些函數~


文件讀寫,寫的話,我認爲相對簡單一點,我們先複習下如何寫文件。

//向文件寫五次hello。
fstream out;
out.open("C:\\Users\\asusa\\Desktop\\藍橋\\wr.txt", ios::out);

if (!out.is_open())
{
    cout << "讀取文件失敗" << endl;
}
string s = "hello";

for (int i = 0; i < 5; ++i)
{
    out << s.c_str() << endl;
}
out.close();

wr.txt文件如下:

hello
hello
hello
hello
hello

如果想要以追加方式寫,只需要open函數的第二個參數改爲app

fstream out;
out.open("C:\\Users\\asusa\\Desktop\\藍橋\\wr.txt", ios::app);

if (!out.is_open())
{
    cout << "讀取文件失敗" << endl;
}
string s = "world";

for (int i = 0; i < 5; ++i)
{
    out << s.c_str() << endl;
}
out.close();

wr.txt文件如下:

hello
hello
hello
hello
hello
world
world
world
world
world

讀文件

讀取文件,主要格式的讀取我覺得有點難,比如

rd.txt
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6

我想要兩種讀取方法,一種是按行讀取,一種是按單詞讀取,讀取的元素都放在vector裏面。

按照行讀取

string filename = "C:\\Users\\asusa\\Desktop\\藍橋\\rd.txt";
fstream fin;
fin.open(filename.c_str(), ios::in);

vector<string> v;
string tmp;

while (getline(fin, tmp))
{
    v.push_back(tmp);
}

for (auto x : v)
    cout << x << endl;

顯示結果如下:

這裏寫圖片描述

按照單詞讀取

string filename = "C:\\Users\\asusa\\Desktop\\藍橋\\rd.txt";
fstream fin;
fin.open(filename.c_str(), ios::in);

vector<string> v;
string tmp;

while (fin >> tmp)
{
    v.push_back(tmp);
}

for (auto x : v)
    cout << x << endl;

結果如下:

這裏寫圖片描述

發佈了96 篇原創文章 · 獲贊 119 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章