如何使用字符串和整数获得字符串
how to get a string using a string and integer?
我想得到这样的输出…
Word_1
Word_2
Word_3
.
.
.
Word_1234
etc...
我见过sprintf
和itoa
等格式化字符串,将int转换为字符串。在sprintf
的情况下,我必须声明大小。有了"Word_"+itoa(iterator_variable)
,我想我可以得到所需要的。但是,有没有更好的方法来获得期望的输出呢?
如果你能访问c++ 11,你可以使用std::to_string()
std::string s = "Word_";
std::string t = s + std::to_string( 1234 );
std::cout << t << std::endl;
使用c++,我喜欢使用boost::format和boost::lexical_cast来解决这类问题。
我推荐使用stringstreams,因为它们允许将任何字符串、流和算术类型(以及其他类型)连接到字符表示中。
#include <sstream>
#include <iostream>
int main()
{
int n1 = 3;
int n2 = 99;
std::stringstream ss;
// all entries in the same stringstream
ss << "Word_" << n1 << std::endl;
ss << "Word_" << n2 << std::endl;
std::cout << ss.str();
// clear
ss.str("");
// entries in individual streams
std::string s1, s2;
ss << "Word_" << n1;
s1 = ss.str();
ss.str("");
ss << "Word_" << n2;
s2 = ss.str();
std::cout << s1 << std::endl << s2 << std::endl;
return 0;
}
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 尝试将字符串/字符转换为整数会产生意外结果
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 如何从C++中的格式化字符串派生整数?
- 如何使用C++将字符串中的字符转换为整数变量
- 向量值(字符串和整数)求和C++
- 如何从字符串C++读取多个整数
- 如何将整数字符串转换为整数的二维向量?
- 输入验证以筛选出字符、字符串和一系列整数
- 有没有办法在C++中将字符串和整数相乘?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- C++字符串大小减去整数不是预期值,为什么?
- 使用字符串流读取整数并将它们相加
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- C++ runtime_exception字符串 + 整数
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- 使用next_permutation函数后如何保存字符串/整数
- 使用fstream和sstream一起从文件中分离字符串/整数