#include<stdio.h>
main()
{
int i=100;
char temp[]="value of i is **** and I can write int inside a string";
printf("\n%s\n",temp);
}
我需要在字符串中打印i
的值。这样我就可以得到输出:
value of i is 100 and I can write int inside a string
我应该在****的地方写什么,或者我应该如何更改此代码以获得上述输出?我不想使用printf
来打印此输出。
答案 0 :(得分:9)
您可以使用sprintf
来打印&#39;字符串转换为char数组,如printf
将其打印到屏幕上:
char temp[256];
sprintf(temp, "value of i is %d and I can write int inside a string", i);
请注意,您需要确保缓冲区足够大!或者使用snprintf
指定最大字符串/文本长度,因此不要在缓冲区外写入。
答案 1 :(得分:4)
printf("value of i is %d and I can write int inside a string\n",100);
如果您不想这样做,请转到
char buf[200];
int i=100;
snprintf(buf,sizeof(buf),"value of i is %d and I can write int inside a string",i);
答案 2 :(得分:2)
这样做的一种安全方法是使用
char temp[256]; /*allocate some storage, currently large enough for the text and a 64 bit int*/
snprintf(temp, sizeof(temp), "value of i is %d and I can write int inside a string", i);
sizeof(temp)
为256. snprintf
一旦达到该大小,就会停止向temp
写入数据;允许空终止符。
我不鼓励使用sprintf
因为它可以超出提供的缓冲区而不安全:snprintf
已成为C标准库的一部分了。
,将原型更改为int main()
,然后返回一个值。 0通常表示成功。
答案 3 :(得分:0)
#include<stdio.h>
main()
{
int i=100;
char temp[]="value of i is %d and I can write int inside a string";
printf(temp,i);
}
试试这个。