2010-09-27 188 views
1

可能重複:
C++ convert int and string to char*C++將int轉換爲字符數組?

你好,我是做一個遊戲,我有一個記分牌在裏面。得分存儲在一個int變量中,但是用於遊戲的庫im需要一個字符數組來爲我的記分板輸出文本。

那麼我如何將一個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 :)

回答

8
ostringstream sout; 
sout << score; 
dbText(100,100, sout.str().c_str()); 
+5

這也是我的建議。請記住.str()返回一個臨時對象,因此緩存.str()。c_str()的結果是一個糟糕的想法。 (這不適用於你的例子,但我想確保提到警告)。 – Tim 2010-09-27 20:44:19

0
char str[10]; 
sprintf(str,"%d",value); 
+0

不要忘記你的分號:D – 2010-09-27 20:44:50

+3

'value = -1000000000' and ... poof!你的代碼不再工作。 – ybungalobill 2010-09-27 20:45:59

+0

@ybungalobill:我確實希望人們使用一個答案來思考並理解他們做了什麼 - 這就是代碼是一個例子的原因......有趣的是,還有一個答案與完全相同的問題沒有投票權給出。 – Shaihi 2010-10-07 15:43:49

2

您可以使用std::ostringstreamint轉換爲std::string,然後用std::string::c_str()到字符串傳遞作爲char陣列給你的函數。

1
char str[16]; 
sprintf(str,"%d",score); 
dbText(100, 100, str); 
0

好吧,如果你想避免C標準庫函數(snprintf等),你可以以通常的方式(std::stringstream等)創建std::string,然後使用string::c_str()得到char *你可以傳遞給圖書館電話。

3

使用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); 

} 
0

讓我知道,如果這有助於。

#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 
}