使用stringstream对象简化类型转换
首先要引入头文件<sstream>,C++标准库中的<sstream>提供了比ANSI C的<stdio.h>更高级的一些功能,即单纯性、类型安全和可扩展性。
<sstream>库是最近才被列入C++标准的。(不要把<sstream>与标准发布前被删掉的<strstream>弄混了。)因此,老一点的编译器,如GCC2.95,并不支持它。如果你恰好正在使用这样的编译器而又想使用<sstream>的话,就要先对它进行升级更新。
<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。简单起见,我主要以stringstream为中心,因为每个转换都要涉及到输入和输出操作。
注意,<sstream>使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险。而且,传入参数和目标对象的类型被自动推导出来,即使使用了不正确的格式化符也没有危险。
一个实例
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
int main(){
//用于存放分割后的字符串
vector<string> res;
//待分割的字符串,含有很多空格
string word=" Hello, I want to learn C++! ";
//暂存从word中读取的字符串
string result;
//将字符串读到input中
stringstream input(word);
//依次输出到result中,并存入res中
while(input>>result)
res.push_back(result);
//输出res
for(int i=0;i<res.size();i++){
cout<<res[i]<<endl;
}
return 0;
}
总结
1. <sstream>还能实现自动类型转换,我会在以后写一些利用它进行数据类型转换的文章。
2. 在C++ Primer书中曾经提到过:
int main(){
string s;
cin>>s;
cout<<s<<endl;
return 0;
}
This program begins by defining a string named s. The next line,
cin>>s
reads the standard input storing what is read into s. The string input operator:
(1) Reads and discards any leading whitespace(e.g.,spaces,mewlines,tabs).
(2) It then reads characters until the next whitespace character is encountered.
也就是说输入的字符串不管有多少空格,传入cin的只有第一个非空白字符下次再遇到空白字符之间的字符串。例如:输入的字符串为” Hello, I want to learn C++! “,则传入cin的只有”Hell0,”。这一点非常重要,必须牢记在心。