fstream库是C++ STL中对文件操作的合集,包含了常用的所有文件操作。在C++中,所有的文件操作,都是以流(stream) 的方式进行的,fstream也就是文件流file stream。
最常用的两种操作为:
1、插入器(<<)——输出到文件流
向流输出数据。比如说打开了一个文件流fout,那么调用
fstream fout;
fout<<"Write to file"<<endl;
就表示把字符串"Write to file"写入文件并换行。
2、析取器(>>)——从文件输入流
从流中输入数据。比如说打开了文件流fin,那么定义整型变量x的情况下
int x;
fstream fin;
fin>>x;
就是从文件中读取一个整型数据,并存储到x中。
sstream库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。
注意:sstream使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险。
1、istringstream的使用
输入流需要输出
#include // std::string
#include // std::cout
#include // std::istringstream
int main () {
std::istringstream in;
std::string str1 = "12 34 5678";
in.str (str1);
for (int n=0; n<4; n++)
{
int val;
in >> val;
std::cout << val << '\n';
}
std::cout << "Finished writing the numbers in: ";
std::cout << in.str() << "\n";
return 0;
}
输出
12
34
5678
5678
Finished writing the numbers in: 12 34 5678
2、ostringstream的使用
输出流需要输入
#include // std::cout
#include // std::ostringstream
int main () {
std::ostringstream out;
for (int n=0; n<4; n++)
{
out<<n;
}
std::cout<<out<< "\n";
return 0;
}
输出
0123
3、stringstream的的使用
输入输出流既可以输出又可以输入
#include // std::string
#include // std::cout
#include // std::stringstream
int main () {
std::stringstream ss;
ss << 100 << ' ' << 200;
int a,b;
ss >> a >> b;
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';
return 0;
}
输出:
a: 100
b: 200
#include
#include
#include
using namespace std;
int main()
{
std::ifstream in("infile0.in");
std::ostringstream tmp;
tmp << in.rdbuf();
std::string str = tmp.str();
cout << str << endl;
}
输出的就是文件中的内容
输入流需要输出
输出流需要输入
输入输出流既可以输出又可以输入
从文件输入流操作就是将流的来源定向到了文件
输出到文件流操作就是将流输出到了文件