整数到字符串转换/整数字符串连接在C ++ - 更紧凑的解决方案? [英] integer to string conversion / integer-string concatenation in C++ - more compact solutions?

查看:168
本文介绍了整数到字符串转换/整数字符串连接在C ++ - 更紧凑的解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何做整数 - >字符串转换已经在互联网上多次回答...但是,我正在寻找最紧凑的C ++ - 方式这样做。

How to do integer -> string conversion has been answered many times on the internet... however, I'm looking for the most compact "C++-way" to do this.

因为你能够使用重载的+运算符连接字符串,所以最好能够沿着python-ish的行做一些事情
x =(stringVariable + str(intVariable) )连接,但我不知道如果有一个规范的方式来做这个在C + +。

Since you're able to concatenate strings using the overloaded + operator, it would be preferable to be able to do something along the lines of the python-ish x = (stringVariable + str(intVariable)) concatenation, but I don't know if there's a canonical way to do this in C++.

我看到的最常见的解决方案是:

The most common solutions I see are:

stringstream:如果可能的话, 3行代码(声明,写入流,转换为字符串)只是为了连接一些字母和数字。

stringstream: If possible, it would be nice not to have 3 lines of code (declaration, writing to the stream, conversion to string) just to concatenate some letters and numbers.

itoa:一个规范的C ++解决方案。此外,我认为itoa在技术上是非标准的,虽然我可能是错误的。

itoa: this works, but I'm looking for a canonical C++ solution. Also, I think itoa is technically non-standard although I could be wrong.

boost格式/ boost词法铸造:这也工作,但在香草C ++

boost format / boost lexical cast: this works too, but is there nothing in vanilla C++ that does the job?

推荐答案

#include <string>

字符串到整数: int n = std :: stoi(s)

整数到字符串: std :: string s = std :: to_string(n);

这篇关于整数到字符串转换/整数字符串连接在C ++ - 更紧凑的解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆