C++ C++;将整数转换为字符数组?
可能重复:C++ C++;将整数转换为字符数组?,c++,arrays,casting,types,char,C++,Arrays,Casting,Types,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
你好,我正在做一个游戏,里面有一个记分板。分数存储在一个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
我使用的图书馆是黑色的
tyvm:)ostringstreamsout;
soutostringstream sout;
sout您可以使用std::ostringstream
将int
转换为std::string
,然后使用std::string::c(u str()
将字符串作为char
数组传递给函数。您可以使用std::ostringstream
将int
转换为std::string
,然后使用std::string::c_str()
将字符串作为char
数组传递给您的函数。好吧,如果您想避免使用c标准库函数(snprintf
等),您可以用通常的方式创建std::string
,然后使用string::c_str()
要获取可传递给库调用的字符*
。如果您想避免使用C标准库函数(snprintf
,等等),可以用通常的方式创建std::string
,然后使用string::C_str()
获取可传递到库调用的字符*
。使用
char str[16];
sprintf(str,"%d",score);
dbText( 100, 100, str );
#包括
int main(){
int score=1234;//存储当前分数
字符缓冲区[50];
sprintf(缓冲区,“%d”,分数);
dbText(100100,缓冲区);
}
使用
#包括
int main(){
int score=1234;//存储当前分数
字符缓冲区[50];
sprintf(缓冲区,“%d”,分数);
dbText(100100,缓冲区);
}
如果有帮助,请告诉我
#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
}
#包括
#包括
使用名称空间std;
int main(){
char-ch[10];
int i=1234;
itoa(i,ch,10);
如果这有帮助,请告诉我
#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
}
#包括
#包括
使用名称空间std;
int main(){
char-ch[10];
int i=1234;
itoa(i,ch,10);
这可能也是我的建议。请记住,.str()返回一个临时对象,因此缓存.str().c_str()的结果是一个坏主意。(这在您的示例中不适用,但我想确定是否提到了警告)。这也是我的建议。请记住,.str()返回一个临时对象,因此缓存.str().c_str()的结果不是一个好主意。(这在您的示例中不适用,但我想确保提到了警告).别忘了你的分号:Dvalue=-1000000000
还有…呸!你的代码不再工作了。@ybungalobill:我确实希望使用答案的人能够思考并理解他们所做的事情-这就是为什么代码是一个例子…有趣的是,还有一个答案与相同的问题没有投反对票。不要或设置分号:Dvalue=-100000000
和…噗!你的代码不再工作了。@ybungalobill:我确实希望使用答案的人思考并理解他们所做的事情-这就是为什么代码是一个例子…有趣的是,还有一个答案与没有投反对票的完全相同的问题。
#include <stdio.h>
int main () {
int score = 1234; // this stores the current score
char buffer [50];
sprintf (buffer, "%d", score);
dbText( 100,100,buffer);
}
#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
}