c++stringstream任意类型转换,用于C++风格的字符串的输入输出

实现任意类型的转换

    template<typename out_type, typename in_value>
    out_type convert(const in_value & t){
      stringstream stream;
      stream<<t;//向流中传值
      out_type result;//这里存储转换结果
      stream>>result;//向result中写入值
      return result;
    }

例子:

#include<iostream>
#include <sstream> 
using namespace std;<pre name="code" class="cpp">int main(){
	string test = "-123 9.87 welcome to, 989, test!";
	istringstream iss;//istringstream提供读 string 的功能
	iss.str(test);//将 string 类型的 test 复制给 iss,返回 void 
	string s;
	cout << "按照空格读取字符串:" << endl;
	while (iss >> s){
		cout << s << endl;//按空格读取string
	}
    system("pause");
    return 0;
}

总结:

1)在istringstream类中,构造字符串流时,空格会成为字符串参数的内部分界;

2)istringstream类可以用作string与各种类型的转换途径

3)ignore函数参数:需要读取字符串的最大长度,需要忽略的字符

发布了68 篇原创文章 · 获赞 141 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/cfl997/article/details/105125804