两种读取方法,一种是按行读取,一种是按单词读取,具体如下:
1、按照行读取
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;
2、按照单词读取
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;
有读取就有写入,下面是写入的方法
//向文件写五次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();
如果文件内容为
black 100
red 200
white 50
black 44
white 33
red 88
如何将数据全部读入