[15.12] 如何将一个值(如,一个数字)转换为 std::string?
有两种方法:可以使用<stdio>工具或<iostream>库。通常,你应该使用<iostream>库。
<iostream> 库允许你使用如下的语法(转换一个double的示例,但你可以替换美妙的多的任何使用<<算符的东西)将任何美妙得多的东西转换为 std::string:
#include <iostream>
#include <sstream>
#include <string>
std::string convertToString(double x)
{
std::ostringstream o;
if (o << x)
return o.str();
// 这儿进行一些错误处理...
return "conversion error";
}
std::ostringstream 对象 o 提供了类似std::cout提供的格式化工具。你可以使用操纵器和格式化标志来控制格式化的结果,就如同你用std::cout可以做到的。
在这个例子中,我们通过被重载了的插入运算符<<,将 x 插入到 o。它调用了iostream的格式化工具将 x 转换为一个std::string。 if 测试保证转换正确工作——对于内建/固有类型,总是成功的,但 if 测试是良好的风格。
表达式os.str()返回包含了被插入到流 o 中的任何东西的std::string ,在这里,是 x 的值的字符串。
[15.13] 如何将 std::string 转换为数值?
[Recently created thanks to Rob Stewart (on 7/00). Click here to go to the next FAQ in the "chain" of recent changes.]
有两种方法:可以使用<stdio>工具或<iostream>库。通常,你应该使用<iostream>库。
<iostream> 库允许你使用如下的语法(转换一个 double的示例,但你可以替换美妙的多的任何能使用 >> 算符被读取的东西)将一个std::string转换为美妙得多的任何东西:
#include <iostream>
#include <sstream>
#include <string>
double convertFromString(const std::string& s)
{
std::istringstream i(s);
double x;
if (i >> x)
return x;
// 这儿进行一些错误处理...
return 0.0;
}
std::istringstream 对象 i 提供了类似std::cin提供的格式化工具。你可以使用操纵器和格式化标志来控制格式化的结果,就如同你用std::cin能做到的。
在这个示例中,我们传递了td::string s来初始化std::istringstream i (例如,s 可能是字符串“123.456”),然后我们通过被重载了的抽取运算符 >>,将 i 抽取到 x。它调用了iostream的格式化工具对字符串进行尽可能的/适当的基于 x 的类型的转换。
if 测试保证了转换正确地工作。例如,如果字符串包含不适合 x 类型的字符,if 测试将失败