8.4
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
ifstream input("F:\\test\\input.txt");//打开文档,string中有'\'应用转义双写
vector<string> Test{};
string temp1;
if (getline(input, temp1))
{
Test.push_back(temp1);
string temp2;
while (getline(input, temp2))
Test.push_back(temp2);
}
else
cerr << "No data!" << endl;
for (auto &i : Test)
{
cout << i << endl;
}
system("pause");
return 0;
}
注意在字符串中,包含'\'应该用转义字符,即双写'\\' 。
8.5
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
ifstream input("F:\\test\\input1.txt");//打开文档,string中有'\'应用转义双写
vector<string> Test{};
string temp1;
if (input>>temp1) //如果获取整行改成getline(input,temp1)即可
{
Test.push_back(temp1);
string temp2;
while (input>>temp2)
Test.push_back(temp2);
}
else
cerr << "No data!" << endl;
for (auto &i : Test)
{
cout << i << endl;
}
system("pause");
return 0;
}
本文展示了如何使用C++标准库中的ifstream类来读取文本文件,并将每行内容存储到vector容器中,最后输出所有内容。通过两种不同方式获取数据:逐行读取与按空格分隔读取。
281

被折叠的 条评论
为什么被折叠?



