25

char*c++ で a に整数をどのように追加しますか?

4

3 に答える 3

29

最初に int をchar*usingに変換しsprintf()ます。

char integer_string[32];
int integer = 1234;

sprintf(integer_string, "%d", integer);

次に、それを他の char* に追加するには、次を使用しますstrcat()

char other_string[64] = "Integer: "; // make sure you allocate enough space to append the other string

strcat(other_string, integer_string); // other_string now contains "Integer: 1234"
于 2008-12-07T02:40:46.417 に答える
11

文字列ストリームを使用することもできます。

char *theString = "Some string";
int theInt = 5;
stringstream ss;
ss << theString << theInt;

文字列は、次を使用してアクセスできます。ss.str();

于 2008-12-07T02:45:29.730 に答える
4

何かのようなもの:

width = floor(log10(num))+1;
result = malloc(strlen(str)+len));
sprintf(result, "%s%*d", str, width, num);

システム上の整数の最大長を使用して、len を単純化できます。

編集おっと-「++」が表示されませんでした。それでも、それは代替手段です。

于 2008-12-07T02:50:26.460 に答える