如何在 C++ 中将数字转换为字符串,反之亦然
由于这个问题每周都会被问到,因此这个常见问题解答可能会对很多用户有所帮助。
如何在 C++ 中将整数转换为字符串
如何在 C++ 中将字符串转换为整数
如何在 C++ 中将浮点数转换为字符串
如何将字符串转换为浮点数C++ 中的数字
Since this question gets asked about every week, this FAQ might help a lot of users.
How to convert an integer to a string in C++
how to convert a string into an integer in C++
how to convert a floating-point number to a string in C++
how to convert a string to a floating-point number in C++
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
C++11 更新
从
C++11
标准开始,字符串到数字的转换(反之亦然)内置于标准库中。以下所有函数都存在于
中(根据第 21.5 段)。字符串到数字
其中每个都将字符串作为输入,并尝试将其转换为数字。如果无法构造有效数字,例如因为没有数字数据或数字超出类型范围,则会引发异常(
std::invalid_argument
或std ::out_of_range
)。如果转换成功且
idx
不为0
,则idx
将包含未用于解码的第一个字符的索引。这可能是最后一个字符后面的索引。最后,整数类型允许指定基数,对于大于 9 的数字,假定使用字母表(
a=10
到z=35
)。您可以找到有关可在此处解析的浮点数、< a href="http://en.cppreference.com/w/cpp/string/basic_string/stol">有符号整数 和 无符号整数。最后,对于每个函数,还有一个重载,它接受 std::wstring 作为第一个参数。
数字到字符串
这些更简单,您传递适当的数字类型并返回一个字符串。对于格式化选项,您应该返回 C++03 stringsream 选项并使用流操纵器,如其他答案中所述。
正如评论中所指出的,这些函数回落到默认的尾数精度,这可能不是最大精度。如果您的应用程序需要更高的精度,最好还是返回其他字符串格式化过程。
还定义了名为
to_wstring
的类似函数,这些函数将返回std::wstring
。Update for C++11
As of the
C++11
standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in<string>
(as per paragraph 21.5).string to numeric
Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (
std::invalid_argument
orstd::out_of_range
).If conversion succeeded and
idx
is not0
,idx
will contain the index of the first character that was not used for decoding. This could be an index behind the last character.Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (
a=10
untilz=35
). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.Finally, for each function there is also an overload that accepts a
std::wstring
as it's first parameter.numeric to string
These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.
As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.
There are also similar functions defined that are named
to_wstring
, these will return astd::wstring
.如何在 C++03 中将数字转换为字符串
itoa
或itof
函数,因为它们是非标准的,因此不可移植。使用字符串流
请注意,您还可以使用字符串流将浮点数转换为字符串,也可以根据需要格式化字符串,就像使用
cout
您可以使用流操纵器,例如
std::endl
、std::hex
和函数std::setw()
,std::set precision()
等使用字符串流,其方式与cout
完全相同
不要将
std::ostringstream
与std::ostrstream
混淆。。后者已被弃用使用增强词法转换 。如果您不熟悉 boost,最好从像 lexical_cast 这样的小型库开始。要下载并安装 boost 及其文档,请转到此处。尽管 boost 不是 C++ 标准,但许多 boost 库最终都得到了标准化,并且 boost 被广泛认为是最好的 C++ 库。
词法转换使用底层的流,所以基本上这个选项与前一个选项相同,只是不那么冗长。
如何在 C++03 中将字符串转换为数字
从 C 继承的最轻量级选项是函数
atoi
(用于整数(按字母顺序到整数))和atof
(对于浮点值(按字母顺序到浮点数))。这些函数采用 C 样式字符串作为参数 (const char *
),因此它们的使用可能被认为是不完全好的 C++ 实践。 cplusplus.com 上有关于 atoi 和 < a href="http://en.cppreference.com/w/cpp/string/byte/atof" rel="noreferrer">atof 包括它们在输入错误时的行为方式。然而,该链接包含一个错误,根据标准,如果输入数字太大而无法适应目标类型,则行为未定义。使用字符串流(这次输入字符串流,
istringstream
)。同样,istingstream 的使用方式与 cin 类似。再次强调,不要将istringstream
与istrstream
混淆。后者已被弃用。使用增强词法转换。
如果输入错误,
lexical_cast
会抛出boost::bad_lexical_cast
类型的异常How to convert a number to a string in C++03
itoa
oritof
functions because they are non-standard and therefore not portable.Use string streams
Note that you can use string streams also to convert floating-point numbers to string, and also to format the string as you wish, just like with
cout
You can use stream manipulators, such as
std::endl
,std::hex
and functionsstd::setw()
,std::setprecision()
etc. with string streams in exactly the same manner as withcout
Do not confuse
std::ostringstream
withstd::ostrstream
. The latter is deprecatedUse boost lexical cast. If you are not familiar with boost, it is a good idea to start with a small library like this lexical_cast. To download and install boost and its documentation go here. Although boost isn't in C++ standard many libraries of boost get standardized eventually and boost is widely considered of the best C++ libraries.
Lexical cast uses streams underneath, so basically this option is the same as the previous one, just less verbose.
How to convert a string to a number in C++03
The most lightweight option, inherited from C, is the functions
atoi
(for integers (alphabetical to integer)) andatof
(for floating-point values (alphabetical to float)). These functions take a C-style string as an argument (const char *
) and therefore their usage may be considered a not exactly good C++ practice. cplusplus.com has easy-to-understand documentation on both atoi and atof including how they behave in case of bad input. However the link contains an error in that according to the standard if the input number is too large to fit in the target type, the behavior is undefined.Use string streams (this time input string stream,
istringstream
). Again, istringstream is used just likecin
. Again, do not confuseistringstream
withistrstream
. The latter is deprecated.Use boost lexical cast.
In case of a bad input,
lexical_cast
throws an exception of typeboost::bad_lexical_cast
在 C++17 中,新函数 std::to_chars 和 std::from_chars 在标头 charconv。
来自 std::to_chars,与 std::from_chars。
虽然编译器没有完全实现它,但它肯定会实现。
In C++17, new functions std::to_chars and std::from_chars are introduced in header charconv.
From std::to_chars, same for std::from_chars.
Although it's not fully implemented by compilers, it definitely will be implemented.
我从 StackOverflow 的某个地方偷了这个方便的类,将任何可流式传输的内容转换为字符串:
然后你将其用作;
相当漂亮!
我还使用这个函数将字符串转换为任何可流式传输的内容,尽管如果您尝试解析不包含数字的字符串,它不是很安全;
(它也不像上一个那么聪明)
用作:
您可能还需要 wstrings 的版本。
I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:
And then you use it as;
Quite nifty!
Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number;
(and its not as clever as the last one either)
Use as:
You might also want versions for wstrings.
如果您仍然将其设计为单独的函数,则更容易编写简单且通用的代码。
If you still design it as a separate function, it's easier to write naive and universal code.