【问题标题】:C++ converting an int to an array of chars? [duplicate]C ++将int转换为字符数组? [复制]
【发布时间】:2011-04-17 23:35:46
【问题描述】:

可能重复:
C++ convert int and string to char*

你好,我正在制作一个游戏,里面有一个记分板。分数存储在一个 int 变量中,但我用于游戏的库需要一个字符数组来输出我的记分牌的文本。

那么我如何将一个 int 变成一个字符数组呢?

int score = 1234;  // this stores the current score

dbText( 100,100, need_the_score_here_but_has_to_be_a_char_array); 
// this function takes in X, Y cords and the text to output via a char array

我使用的库是 DarkGDK。

tyvm :)

【问题讨论】:

    标签: c++ arrays casting types char


    【解决方案1】:
    char str[10];  
    sprintf(str,"%d",value);
    

    【讨论】:

    • 别忘了你的分号 :D
    • value = -1000000000 和...噗!您的代码不再有效。
    • @ybungalobill:我确实希望人们使用答案来思考和理解他们所做的事情 - 这就是为什么代码是一个例子......有趣的是还有另一个答案与完全相同的问题没有投反对票。
    【解决方案2】:
    ostringstream sout;
    sout << score;
    dbText(100,100, sout.str().c_str());
    

    【讨论】:

    • 这也是我的建议。请记住 .str() 返回一个临时对象,因此缓存 .str().c_str() 的结果是一个坏主意。 (这不适用于您的示例,但我想确保提到了警告)。
    【解决方案3】:

    您可以使用std::ostringstreamint 转换为std::string,然后使用std::string::c_str() 将字符串作为char 数组传递给您的函数。

    【讨论】:

      【解决方案4】:
      char str[16];
      sprintf(str,"%d",score);
      dbText( 100, 100, str );
      

      【讨论】:

        【解决方案5】:

        好吧,如果你想避免 C 标准库函数(snprintf 等),你可以以通常的方式(std::stringstream 等)创建一个std::string,然后使用string::c_str() 来获取char *,您可以将其传递给库调用。

        【讨论】:

          【解决方案6】:

          使用sprintf

          #include <stdio.h>
          
          int main () {
            int score = 1234; // this stores the current score
            char buffer [50];
            sprintf (buffer, "%d", score);
            dbText( 100,100,buffer);
          
          }
          

          【讨论】:

            【解决方案7】:

            如果这有帮助,请告诉我。

            #include <iostream>
            #include <stdlib.h>
            using namespace std;
            
            int main() {
                char ch[10];
                int i = 1234;
                itoa(i, ch, 10);
                cout << ch[0]<<ch[1]<<ch[2]<<ch[3] << endl; // access one char at a time
                cout << ch << endl; // print the whole thing
            }
            

            【讨论】:

              猜你喜欢
              • 2013-11-12
              • 2014-07-05
              • 1970-01-01
              • 2018-11-09
              • 2010-09-17
              • 2019-03-10
              • 1970-01-01
              • 2016-08-13
              • 2014-03-23
              相关资源
              最近更新 更多