1 istringstream和ostringstream
标准库中提供了相关的类对字符串和数字进行转换:字符串流类(sstream)用于string的转换。

1.1 istringstream:string转数字

1.2 ostringstream:数字转string

字符串和数字的转换:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
#define TO_NUMBER(s, n) (istringstream(s) >> n)
#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str())
int main()
{
double n = 0;
if( TO_NUMBER("234.567", n) )
{
cout << n << endl;
}
string s = TO_STRING(12345);
cout << s << endl;
return 0;
}
参考资料:
本文介绍了C++中使用istringstream和ostringstream进行字符串与数字互相转换的方法。通过定义宏TO_NUMBER和TO_STRING,实现从string到数字类型及从数字类型到string的转换。代码示例展示了如何将234.567转换为double类型,以及如何将整数12345转换为string。
524

被折叠的 条评论
为什么被折叠?



