如何使用字符串和整数获得字符串

how to get a string using a string and integer?

本文关键字:字符串 整数 何使用      更新时间:2023-10-16

我想得到这样的输出…

Word_1
Word_2
Word_3
.
.
.
Word_1234
etc...

我见过sprintfitoa等格式化字符串,将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;
}