【问题标题】:How do you append an int to a string in C++? [duplicate]如何在 C++ 中将 int 附加到字符串? [复制]
【发布时间】:2010-09-09 01:13:16
【问题描述】:
int i = 4;
string text = "Player ";
cout << (text + i);

我希望它打印Player 4

以上显然是错误的,但它显示了我在这里尝试做的事情。有没有一种简单的方法可以做到这一点,还是我必须开始添加新的包含?

【问题讨论】:

  • 另外,这里正确的词是'连接/附加一个整数到一个字符串'
  • 您可以逐位附加到字符串..

标签: c++ int stdstring


【解决方案1】:

使用 C++11,您可以编写:

#include <string>     // to use std::string, std::to_string() and "+" operator acting on strings 

int i = 4;
std::string text = "Player ";
text += std::to_string(i);

【讨论】:

    【解决方案2】:
    printf("Player %d", i);
    

    (随便投反对票;我仍然讨厌 C++ I/O 运算符。)

    :-P

    【讨论】:

    • 这个答案的问题是,它“打印”字符串和 int,这不会附加它,在 c++ 中,您可能希望将值输出到与“cout”不同的流中,这是不可能的使用 printf。
    • @Kyborek - 我用相同的方式回答了这个问题。如果您真的想追加而不是打印,那么还有一组标准函数库可以做到这一点。例如,请参阅 sprintf 及其安全变体 (msdn.microsoft.com/en-us/library/vstudio/ybk95axf.aspx)。
    • 根据 Eric 的评论:char cstr[10];sprintf(cstr,"Player %d",i);char *cstr;asprintf(cstr,"Player %d",i);
    【解决方案3】:

    这些适用于一般字符串(如果您不想输出到文件/控制台,而是存储以供以后使用或其他东西)。

    boost.lexical_cast

    MyStr += boost::lexical_cast<std::string>(MyInt);
    

    字符串流

    //sstream.h
    std::stringstream Stream;
    Stream.str(MyStr);
    Stream << MyInt;
    MyStr = Stream.str();
    
    // If you're using a stream (for example, cout), rather than std::string
    someStream << MyInt;
    

    【讨论】:

      【解决方案4】:

      我能想到的最简单的方法是以下..
      它将作为单个字符串字符串数组工作。 我正在考虑一个字符串数组,因为它很复杂(字符串后面会有一点点相同)。 我创建了一个名称数组并 append 一些整数和 char 以显示将一些 intchars 附加到字符串是多么容易,希望能帮助到你。 length 只是衡量数组的大小。如果您熟悉编程,那么 size_t 是一个无符号 int

      #include<iostream>
          #include<string>
          using namespace std;
          int main() {
      
              string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array
              int length = sizeof(names) / sizeof(names[0]); //give you size of array
              int id;
              string append[7];    //as length is 7 just for sake of storing and printing output 
              for (size_t i = 0; i < length; i++) {
                  id = rand() % 20000 + 2;
                  append[i] = names[i] + to_string(id);
              }
              for (size_t i = 0; i < length; i++) {
                  cout << append[i] << endl;
              }
      
      
      }
      

      【讨论】:

      • 这个问题被回答了好几次,已经超过 7 年了,不够简洁。您对这段代码的意图是什么,它也打破了如何结束 cpp 程序的最低标准? system("pause") 在某些计算机系统上不明确。请考虑。
      【解决方案5】:

      您还可以尝试将玩家的号码与std::string::push_back 连接起来:

      代码示例:

      int i = 4;
      string text = "Player ";
      text.push_back(i + '0');
      cout << text;
      

      你会在控制台看到:

      玩家 4

      【讨论】:

      • 这不适用于大于 9 的整数
      【解决方案6】:

      如果您的问题需要,这里的一种方法是直接打印输出。

      cout << text << i;
      

      否则,最安全的方法之一是使用

      sprintf(count, "%d", i);
      

      然后将其复制到您的“文本”字符串中。

      for(k = 0; *(count + k); k++)
      { 
        text += count[k]; 
      } 
      

      这样,你就有了你需要的输出字符串

      有关sprintf的更多信息,请关注: http://www.cplusplus.com/reference/cstdio/sprintf

      【讨论】:

        【解决方案7】:

        您的示例似乎表明您希望显示一个字符串后跟一个整数,在这种情况下:

        string text = "Player: ";
        int i = 4;
        cout << text << i << endl;
        

        可以正常工作。

        但是,如果您要存储字符串位置或传递它,并且经常这样做,您可能会从重载加法运算符中受益。我在下面演示:

        #include <sstream>
        #include <iostream>
        using namespace std;
        
        std::string operator+(std::string const &a, int b) {
          std::ostringstream oss;
          oss << a << b;
          return oss.str();
        }
        
        int main() {
          int i = 4;
          string text = "Player: ";
          cout << (text + i) << endl;
        }
        

        实际上,您可以使用模板来使这种方法更强大:

        template <class T>
        std::string operator+(std::string const &a, const T &b){
          std::ostringstream oss;
          oss << a << b;
          return oss.str();
        }
        

        现在,只要对象 b 具有定义的流输出,您就可以将其附加到您的字符串(或至少是其副本)。

        【讨论】:

        • 您如何避免现在使用模板化解决方案std::string("a") + std::string("b") 模棱两可的编译错误?
        • 这将如何工作?我认为除非您至少有一个用户定义的类,否则不允许重载运算符?
        • @JaisonTitus:它编译和运行没有警告或错误。如果您能找到您的信念的来源,例如标准或其他说明这是被禁止的文件,我很乐意尝试解决这个问题。
        • 好吧,我正试图这样做。基本上,我想在字符串上重载 + 以便我可以执行类似 foo("mystring"+val) 的操作,其中 val 是 int 类型,而 foo 是 void foo(string message);我尝试使用您提供的内容,但出现编译器错误,提示“将 int 添加到字符串不会附加到字符串”。我不确定我在哪里读到这不适用于原始类型,但原因是,如果允许这样做,任何标头都可以理想地覆盖原始类型的运算符的功能,您将不知道这是在哪里发生的。我会试着找到链接。
        • @JaisonTitus:我不确定 std::string 是否符合原始类型,尽管 char 数组是。我可以明白为什么它可以被认为是一种不好的做法,当然。如果您仍然遇到您提到的问题,请随时将其作为问题提交并将链接放在这里。我很乐意看看。
        【解决方案8】:

        为了记录,你也可以使用 Qt 的 QString 类:

        #include <QtCore/QString>
        
        int i = 4;
        QString qs = QString("Player %1").arg(i);
        std::cout << qs.toLocal8bit().constData();  // prints "Player 4"
        

        【讨论】:

        • 为了完整起见,等价的是:std::cout
        【解决方案9】:

        作为记录,如果您想在实际输出之前创建字符串,也可以使用std::stringstream

        【讨论】:

          【解决方案10】:

          好吧,如果你使用 cout,你可以直接将整数写入它,如下所示

          std::cout << text << i;
          

          C++将各种对象转换为字符串的方式是通过string streams。如果您手边没有一个,只需创建一个。

          #include <sstream>
          
          std::ostringstream oss;
          oss << text << i;
          std::cout << oss.str();
          

          或者,您可以只转换整数并将其附加到字符串。

          oss << i;
          text += oss.str();
          

          最后,Boost 库提供了boost::lexical_cast,它使用类似于内置类型转换的语法围绕字符串流转换。

          #include <boost/lexical_cast.hpp>
          
          text += boost::lexical_cast<std::string>(i);
          

          这也适用于其他方式,即解析字符串。

          【讨论】:

            【解决方案11】:

            你可以使用下面的

            int i = 4;
            string text = "Player ";
            text+=(i+'0');
            cout << (text);
            

            【讨论】:

              【解决方案12】:

              另一种可能是Boost.Format:

              #include <boost/format.hpp>
              #include <iostream>
              #include <string>
              
              int main() {
                int i = 4;
                std::string text = "Player";
                std::cout << boost::format("%1% %2%\n") % text % i;
              }
              

              【讨论】:

                【解决方案13】:

                这是一个小的工作转换/附加示例,其中包含我之前需要的一些代码。

                #include <string>
                #include <sstream>
                #include <iostream>
                
                using namespace std;
                
                int main(){
                string str;
                int i = 321;
                std::stringstream ss;
                ss << 123;
                str = "/dev/video";
                cout << str << endl;
                cout << str << 456 << endl;
                cout << str << i << endl;
                str += ss.str();
                cout << str << endl;
                }
                

                输出将是:

                /dev/video
                /dev/video456
                /dev/video321
                /dev/video123
                

                请注意,在最后两行中,您在实际打印输出之前保存了修改后的字符串,如果需要,您可以稍后使用它。

                【讨论】:

                  【解决方案14】:

                  如果使用 Windows/MFC,并且需要字符串而不是立即输出,请尝试:

                  int i = 4;
                  CString strOutput;
                  strOutput.Format("Player %d", i);
                  

                  【讨论】:

                    【解决方案15】:
                    cout << text << " " << i << endl;
                    

                    【讨论】:

                      【解决方案16】:
                      cout << "Player" << i ;
                      

                      【讨论】:

                        【解决方案17】:
                        cout << text << i;
                        

                        ostream 的 &lt;&lt; 运算符返回对 ostream 的引用,因此您可以继续链接 &lt;&lt; 操作。也就是与上面基本相同:

                        cout << text;
                        cout << i;
                        

                        【讨论】:

                          【解决方案18】:
                          cout << text << i;
                          

                          【讨论】:

                            【解决方案19】:

                            有几个选项,你想要哪一个取决于上下文。

                            最简单的方法是

                            std::cout << text << i;
                            

                            或者如果你想把它放在一行中

                            std::cout << text << i << endl;
                            

                            如果您正在编写一个单线程程序,并且您没有经常调用此代码(其中“很多”是每秒数千次),那么您就完成了。

                            如果您正在编写一个多线程程序并且多个线程正在写入 cout,那么这个简单的代码可能会给您带来麻烦。让我们假设您的编译器附带的库使 cout 线程足够安全,以至于对它的任何单个调用都不会被中断。现在假设一个线程正在使用此代码编写“Player 1”,另一个正在编写“Player 2”。如果幸运的话,您将获得以下信息:

                            Player 1
                            Player 2
                            

                            如果你运气不好,你可能会得到类似下面的东西

                            Player Player 2
                            1
                            

                            问题在于 std::cout

                            std::cout << text;
                            std::cout << i;
                            std::cout << endl;
                            

                            如果您改为使用 C 风格的 printf,并且您的编译器再次提供了一个具有合理线程安全性的运行时库(每个函数调用都是原子的),那么下面的代码会更好地工作:

                            printf("Player %d\n", i);
                            

                            能够在单个函数调用中做某事让 io 库在后台提供同步,现在您的整行文本将被原子写入。

                            对于简单的程序,std::cout 很棒。加上多线程或其他复杂性,不那么时尚的 printf 开始看起来更具吸引力。

                            【讨论】:

                              【解决方案20】:
                              cout << text << " " << i << endl;
                              

                              【讨论】:

                                猜你喜欢
                                • 1970-01-01
                                • 1970-01-01
                                • 2021-10-04
                                • 2020-11-18
                                • 2017-11-11
                                • 1970-01-01
                                • 2021-10-25
                                • 1970-01-01
                                相关资源
                                最近更新 更多