前段时间参加蓝桥杯,遇到一些题目,题目本身不难,按照常规思路写代码即可,但是我忘了如何读取文件了。。。面对一堆数据楞是写不出。还有几天是蓝桥杯的决赛,所以为了避免踩同样的坑,我打算通过实例复习下文件读写。
文件读写需要引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;
结果如下: