#include 是C++的预编译语句,作用是包含对应的文件,在这里是包含C++的STL头文件fstream。
在包含了这个文件后,就可以使用fstream中定义的类及各种成员函数了。
fstream是C++ STL中对文件操作的合集,包含了常用的所有文件操作。在C++中,所有的文件操作,都是以流(stream) 的方式进行的,
fstream也就是文件流file stream。
最常用的两种操作为:
1、插入器(<<)
向流输出数据。比如说打开了一个文件流fout,那么调用fout<<"Write to file"<<endl;就表示把字符串"Write to file"写入文件并换行。
2、析取器(>>)
从流中输入数据。比如说打开了文件流fin,那么定义整型变量x的情况下,fin>>x;就是从文件中读取一个整型数据,并存储到x中。
<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。注意,<sstream>使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险。而且,传入参数和目标对象的类型被自动推导出来,即使使用了不正确的格式化符也没有危险。
istringstream的用法
- #include <string> // std::string
- #include <iostream> // std::cout
- #include <sstream> // std::istringstream
-
- int main () {
- std::istringstream iss;
- std::string strvalues = "32 240 2 1450";
-
- iss.str (strvalues);
-
- for (int n=0; n<4; n++)
- {
- int val;
- iss >> val;
- std::cout << val << '\n';
- }
- std::cout << "Finished writing the numbers in: ";
- std::cout << iss.str() << '\n';
- return 0;
stringstream的用法
-
- #include <string> // std::string
- #include <iostream> // std::cout
- #include <sstream> // std::stringstream
-
- int main () {
-
- std::stringstream ss;
-
- ss << 100 << ' ' << 200;
-
- int foo,bar;
- ss >> foo >> bar;
-
- std::cout << "foo: " << foo << '\n';
- std::cout << "bar: " << bar << '\n';
-
- return 0;
- }