首页 文章

如何连接std :: string和int?

提问于
浏览
583

我认为这很简单,但它会带来一些困难 . 如果我有

std::string name = "John";
int age = 21;

如何组合它们以获得单个字符串 "John21"

29 回答

  • 3
    #include <sstream>
    
    template <class T>
    inline std::string to_string (const T& t)
    {
       std::stringstream ss;
       ss << t;
       return ss.str();
    }
    

    然后你的用法看起来像这样

    std::string szName = "John";
       int numAge = 23;
       szName += to_string<int>(numAge);
       cout << szName << endl;
    

    Googled [并测试过:p]

  • 12

    按字母顺序排列:

    std::string name = "John";
    int age = 21;
    std::string result;
    
    // 1. with Boost
    result = name + boost::lexical_cast<std::string>(age);
    
    // 2. with C++11
    result = name + std::to_string(age);
    
    // 3. with FastFormat.Format
    fastformat::fmt(result, "{0}{1}", name, age);
    
    // 4. with FastFormat.Write
    fastformat::write(result, name, age);
    
    // 5. with the {fmt} library
    result = fmt::format("{}{}", name, age);
    
    // 6. with IOStreams
    std::stringstream sstm;
    sstm << name << age;
    result = sstm.str();
    
    // 7. with itoa
    char numstr[21]; // enough to hold all numbers up to 64-bits
    result = name + itoa(age, numstr, 10);
    
    // 8. with sprintf
    char numstr[21]; // enough to hold all numbers up to 64-bits
    sprintf(numstr, "%d", age);
    result = name + numstr;
    
    // 9. with STLSoft's integer_to_string
    char numstr[21]; // enough to hold all numbers up to 64-bits
    result = name + stlsoft::integer_to_string(numstr, 21, age);
    
    // 10. with STLSoft's winstl::int_to_string()
    result = name + winstl::int_to_string(age);
    
    // 11. With Poco NumberFormatter
    result = name + Poco::NumberFormatter().format(age);
    
    • 是安全的,但很慢;需要Boost(仅限 Headers );大多数/所有平台

    • 是安全的,需要C 11(to_string()已包含在 #include <string> 中)

    • 安全,快速;需要FastFormat,必须编译;大多数/所有平台

    • 安全,快速;需要FastFormat,必须编译;大多数/所有平台

    • 安全,快速;需要the library,可以在仅头模式下编译或使用;大多数/所有平台

    • 安全,缓慢,冗长;需要 #include <sstream> (来自标准C)

    • 很脆弱(你必须提供足够大的缓冲区),快速,冗长; itoa()是非标准扩展,并不保证可用于所有平台

    • 很脆弱(你必须提供足够大的缓冲区),快速,冗长;什么都不需要(标准C);所有平台

    • 很脆弱(你必须提供足够大的缓冲区),probably the fastest-possible conversion,详细;需要STLSoft(仅限 Headers );大多数/所有平台

    • safe-ish(您不会在单个语句中使用多个int_to_string()调用),速度快;需要STLSoft(仅限 Headers );仅Windows

    • 是安全的,但很慢;需要Poco C++;大多数/所有平台

  • 5

    在C 11中,您可以使用 std::to_string ,例如:

    auto result = name + std::to_string( age );
    
  • 1

    如果你有Boost,你可以使用 boost::lexical_cast<std::string>(age) 将整数转换为字符串 .

    另一种方法是使用stringstreams:

    std::stringstream ss;
    ss << age;
    std::cout << name << ss.str() << std::endl;
    

    第三种方法是使用C库中的 sprintfsnprintf .

    char buffer[128];
    snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
    std::cout << buffer << std::endl;
    

    其他海报建议使用 itoa . 这不是标准功能,因此如果您使用它,您的代码将无法移植 . 有些编译器不支持它 .

  • 15
    std::ostringstream o;
    o << name << age;
    std::cout << o.str();
    
  • 3
    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    string itos(int i) // convert int to string
    {
        stringstream s;
        s << i;
        return s.str();
    }
    

    http://www.research.att.com/~bs/bs_faq2.html无耻地偷走了 .

  • 7

    这是最简单的方法:

    string s = name + std::to_string(age);
    
  • 81

    在我看来,最简单的答案是使用 sprintf 函数:

    sprintf(outString,"%s%d",name,age);
    
  • 4

    如果你有C 11,你可以使用 std::to_string .

    例:

    std::string name = "John";
    int age = 21;
    
    name += std::to_string(age);
    
    std::cout << name;
    

    输出:

    John21
    
  • 985
    #include <string>
    #include <sstream>
    using namespace std;
    string concatenate(std::string const& name, int i)
    {
        stringstream s;
        s << name << i;
        return s.str();
    }
    
  • 4

    Herb Sutter有一篇关于这个主题的好文章:"The String Formatters of Manor Farm" . 他介绍了 Boost::lexical_caststd::stringstreamstd::strstream (已弃用)和 sprintfsnprintf .

  • -5

    如果您想使用 + 连接任何具有输出运算符的内容,则可以提供 operator+ 的模板版本:

    template <typename L, typename R> std::string operator+(L left, R right) {
      std::ostringstream os;
      os << left << right;
      return os.str();
    }
    

    然后你可以用一种简单的方式编写你的连接:

    std::string foo("the answer is ");
    int i = 42;
    std::string bar(foo + i);    
    std::cout << bar << std::endl;
    

    输出:

    the answer is 42
    

    这不是最有效的方法,但除非你在循环中进行大量连接,否则不需要最有效的方法 .

  • 26

    如果您使用的是MFC,则可以使用CString

    CString nameAge = "";
    nameAge.Format("%s%d", "John", 21);
    

    托管C也有一个string formatter .

  • 73

    std :: ostringstream是一个很好的方法,但有时这个额外的技巧可以方便地将格式转换为单行:

    #include <sstream>
    #define MAKE_STRING(tokens) /****************/ \
        static_cast<std::ostringstream&>(          \
            std::ostringstream().flush() << tokens \
        ).str()                                    \
        /**/
    

    现在您可以格式化这样的字符串:

    int main() {
        int i = 123;
        std::string message = MAKE_STRING("i = " << i);
        std::cout << message << std::endl; // prints: "i = 123"
    }
    
  • 0

    由于Qt相关的问题被关闭而支持这个问题,这里是如何使用Qt做到的:

    QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
    string.append(someOtherIntVariable);
    

    字符串变量现在具有someIntVariable的值代替%1和someOtherIntVariable的结尾值 .

  • -1

    常见答案:itoa()

    这是不好的 . itoa 是非标准的,正如here所指出的那样 .

  • 49

    您可以使用下面给出的简单技巧将int连接到字符串,但请注意,这仅在整数为单个数字时有效 . 否则,将数字逐位添加到该字符串 .

    string name = "John";
    int age = 5;
    char temp = 5 + '0';
    name = name + temp;
    cout << name << endl;
    
    Output:  John5
    
  • 19

    有更多选项可用于将整数(或其他数字对象)与字符串连接起来 . 这是Boost.Format

    #include <boost/format.hpp>
    #include <string>
    int main()
    {
        using boost::format;
    
        int age = 22;
        std::string str_age = str(format("age is %1%") % age);
    }
    

    和来自Boost.Spirit的Karma(v2)

    #include <boost/spirit/include/karma.hpp>
    #include <iterator>
    #include <string>
    int main()
    {
        using namespace boost::spirit;
    
        int age = 22;
        std::string str_age("age is ");
        std::back_insert_iterator<std::string> sink(str_age);
        karma::generate(sink, int_, age);
    
        return 0;
    }
    

    Boost.Spirit Karma声称是fastest option for integer to string转换之一 .

  • 4

    如果你想得到一个char * out,并按照上面的响应者所概述的那样使用了stringstream,那么就这样做:

    myFuncWhichTakesPtrToChar(ss.str().c_str());
    

    由于stringstream通过str()返回的是一个标准字符串,因此可以在其上调用c_str()以获得所需的输出类型 .

  • 3

    我写了一个函数,它以int数作为参数,并将其转换为字符串文字 . 此函数依赖于将单个数字转换为其等效字符的另一个函数:

    char intToChar(int num)
    {
        if (num < 10 && num >= 0)
        {
            return num + 48;
            //48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)
        }
        else
        {
            return '*';
        }
    }
    
    string intToString(int num)
    {
        int digits = 0, process, single;
        string numString;
        process = num;
    
        // The following process the number of digits in num
        while (process != 0)
        {
            single  = process % 10; // 'single' now holds the rightmost portion of the int
            process = (process - single)/10;
            // Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10
            // The above combination eliminates the rightmost portion of the int
            digits ++;
        }
    
        process = num;
    
        // Fill the numString with '*' times digits
        for (int i = 0; i < digits; i++)
        {
            numString += '*';
        }
    
    
        for (int i = digits-1; i >= 0; i--)
        {
            single = process % 10;
            numString[i] = intToChar ( single);
            process = (process - single) / 10;
        }
    
        return numString;
    }
    
  • 2

    下面是如何使用IOStreams库中的解析和格式化方面将int附加到字符串的实现 .

    #include <iostream>
    #include <locale>
    #include <string>
    
    template <class Facet>
    struct erasable_facet : Facet
    {
        erasable_facet() : Facet(1) { }
        ~erasable_facet() { }
    };
    
    void append_int(std::string& s, int n)
    {
        erasable_facet<std::num_put<char,
                                    std::back_insert_iterator<std::string>>> facet;
        std::ios str(nullptr);
    
        facet.put(std::back_inserter(s), str,
                                         str.fill(), static_cast<unsigned long>(n));
    }
    
    int main()
    {
        std::string str = "ID: ";
        int id = 123;
    
        append_int(str, id);
    
        std::cout << str; // ID: 123
    }
    
  • 0
    • std :: ostringstream

    #include <sstream>

    std :: ostringstream s;
    s <<“John”<<年龄;
    std :: string query(s.str());

    • std :: to_string(C 11)

    std :: string query(“John”std :: to_string(age));

    • boost :: lexical_cast

    #include <boost / lexical_cast.hpp>

    std :: string查询(“John”升压:: lexical_cast的<的std :: string>(年龄));

  • 2

    这个问题可以通过多种方式完成 . 我将以两种方式展示它:

    • 使用to_string(i)将数字转换为字符串 .

    • 使用字符串流 .

    码:

    #include <string>
    #include <sstream>
    #include <bits/stdc++.h>
    #include <iostream>
    using namespace std;
    
    int main() {
        string name = "John";
        int age = 21;
    
        string answer1 = "";
        // Method 1). string s1 = to_string(age).
    
        string s1=to_string(age); // Know the integer get converted into string
        // where as we know that concatenation can easily be done using '+' in C++
    
        answer1 = name + s1;
    
        cout << answer1 << endl;
    
        // Method 2). Using string streams
    
        ostringstream s2;
    
        s2 << age;
    
        string s3 = s2.str(); // The str() function will convert a number into a string
    
        string answer2 = "";  // For concatenation of strings.
    
        answer2 = name + s3;
    
        cout << answer2 << endl;
    
        return 0;
    }
    

    // 希望能帮助到你

  • 237

    另一种简单的方法是:

    name.append(age+"");
    cout << name;
    
  • 18

    detailed answer被埋没在其他答案之下,重新铺设部分答案:

    #include <iostream> // cout
    #include <string> // string, to_string(some_number_here)
    
    using namespace std;
    
    int main() {
        // using constants
        cout << "John" + std::to_string(21) << endl;
        // output is:
        //    John21
    
        // using variables
        string name = "John";
        int age = 21;
        cout << name + to_string(age) << endl;
        // output is:
        //    John21
    }
    
  • 4

    随着library

    auto result = fmt::format("{}{}", name, age);
    

    该库的一个子集被建议用于标准化为P0645 Text Formatting,如果被接受,上述内容将变为:

    auto result = std::format("{}{}", name, age);
    

    Disclaimer :我是库的作者 .

  • 2

    没有C 11,对于一个小的整数范围,我发现这就是我所需要的:

    在某处声明/包含以下某些变体:

    const string intToString[10] = {"0","1","2","3","4","5","6","7","8","9"};
    

    然后:

    string str = intToString[3] + " + " + intToString[4] + " = " + intToString[7]; //str equals "3 + 4 = 7"
    

    它也适用于枚举 .

  • 11

    为像我这样可能无法访问C 11的人以及像boost这样的其他库/ Headers 建议一个替代解决方案 . 一个简单的转换工作如下:

    示例数字为4,要将3转换为ascii,我们可以简单地使用代码:
    char a = '0' 4

    这将立即将4作为角色存储在a中 .

    从这里,我们可以简单地将a与字符串的其余部分连接起来 .

  • 1

    我是初学C用户,发现这是最简单的方法:

    cout << name << age;
    

    这将成功连接名称和年龄,输出将为“John21” .

    然而,没有人说这个的原因;我认为虽然到目前为止我还没有遇到任何问题,但可能存在缺陷 .

    编辑:我已经意识到这不一定是正确的答案,但是我会保留它,以防任何C初学者想知道如何输出连接字符串 .

相关问题