C++中檔案讀取處理(按行或者單詞)
阿新 • • 發佈:2019-01-22
前段時間參加藍橋杯,遇到一些題目,題目本身不難,按照常規思路寫程式碼即可,但是我忘了如何讀取檔案了。。。面對一堆資料楞是寫不出。還有幾天是藍橋杯的決賽,所以為了避免踩同樣的坑,我打算通過例項複習下檔案讀寫。
檔案讀寫需要引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;
結果如下: