现在的位置: 首页 > 综合 > 正文

string与数值类型的转换以及stringstream的注意点

2018年05月08日 ⁄ 综合 ⁄ 共 665字 ⁄ 字号 评论关闭
#include <sstream>
#include <iostream>

template<typename ValueType>
void convertStringToAnyValue(const std::string& strValue, ValueType& val)
{
	std::stringstream  ss(strValue);
	ss >> val;
}

template<typename ValueType>
void convertAnyValueToString(std::string& strValue, ValueType val)
{
	std::stringstream ss;
	ss << val;
	ss >> strValue;
}

int main(int argc, char** argv)
{
	std::stringstream ss("1");
	std::cout << ss.str() << std::endl; //1
	ss << "2"; // "1" 被2覆盖
	std::cout << ss.str() << std::endl; //2
	ss << "3";	// “3”串接在"2"之后
	std::cout << ss.str() << std::endl; // 23

	ss.clear();
	std::cout << ss.str() << std::endl; // 23 注意:依然为23
	ss << "4";
	std::cout << ss.str() << std::endl; // 234

	ss.str("5");
	std::cout << ss.str() << std::endl; // 5, "5"替换掉了原先的"234"
	
	return 0;
}

抱歉!评论已关闭.