【cpp】chap 8

时间:2023-03-08 16:13:59

1.输出“输入的内容”

// basic file operations
#include <iostream>
#include <fstream>
#include <string>
using namespace std; std::istream& func(std::istream &is)
{
std::string buf;
while (is >> buf)
std::cout << "output = " << buf << std::endl;
is.clear();
return is;
} int main() {
std::istream &is=cin;
func(is);
}

2.istringstream

#include <iostream>
#include <sstream>
using std::istream; istream& func(istream &is)
{
std::string buf;
while (is >> buf)
std::cout << buf << std::endl;
is.clear();
return is;
} int main()
{
std::istringstream iss("hello");
func(iss); system("pause");
return ;
}

3.ReadFileToVec——将每一行储存成为vector元素

#include <fstream>
#include <string>
#include <vector>
#include <iostream> using std::vector; using std::string; using std::ifstream; using std::cout; using std::endl; void ReadFileToVec(const string& fileName, vector<string>& vec)
{
ifstream ifs(fileName);
if (ifs)
{
string buf;
while (std::getline(ifs, buf))
vec.push_back(buf);
}
} int main()
{
vector<string> vec;
ReadFileToVec("cww.txt", vec);
for (const auto &str : vec)
cout << str << endl;
system("pause");
return ;
}

将每个单词存储到vector元素:

#include <fstream>
#include <string>
#include <vector>
#include <iostream> using std::vector; using std::string; using std::ifstream; using std::cout; using std::endl; void ReadFileToVec(const string& fileName, vector<string>& vec)
{
ifstream ifs(fileName);
if (ifs)
{
string buf;
while (ifs >> buf)
vec.push_back(buf);
}
} int main()
{
vector<string> vec;
ReadFileToVec("cww.txt", vec);
for (const auto &str : vec)
cout << str << endl;
system("pause");
return ;
}

4.除非有必须使用其他容器的理由,否则就用Vector或List。

5.