string对象与数值的转换

#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;

string convertToString(double x)
{
	ostringstream o;
	if(o<<x)
		return o.str();
	return "error";
}


double convertFromString(const string &s)
{
	istringstream i(s);
	double x;
	if(i>>x)
		return x;
	return 0.0;
}


int main()
{
	//c方法,编译器警告
	char b[10];
	string a;
	sprintf(b,"%d",2012);
	a=b;
	cout<<a;

	//c++
	string aa=convertToString(2011);
	cout<<aa;

	//c++
	string dd="2010";
	double ee=convertFromString(dd);
	cout<<ee;

	system("pause");
	return 0;
}

另,注意string中erase()方法的第二个参数位置,和find()方法的返回值



ref: 《ACM程序设计》

你可能感兴趣的:(string对象与数值的转换)