如何在c中将int变量更改为字符串变量?

如何在c中将int变量更改为字符串变量?,c,string,file,text,structure,C,String,File,Text,Structure,阅读问题“我需要能够扫描一个int值并将其作为字符串变量打印回来”如果您只想将其打印回来,则可以在使用printf时使用“%d”说明符。如果您想将整数值转换为字符串用于其他目的,可以使用itoa。您可以使用sprintf函数来实现 int a; // [log(2^63 - 1)] + 1 = 19 where // [x] is the greatest integer <= x // +1 for the terminating null byte char s[19+1]; /

阅读问题“我需要能够扫描一个int值并将其作为字符串变量打印回来”

如果您只想将其打印回来,则可以在使用printf时使用“%d”说明符。如果您想将整数值转换为字符串用于其他目的,可以使用itoa。

您可以使用
sprintf
函数来实现

int a;
// [log(2^63 - 1)] + 1  = 19 where
// [x] is the greatest integer <= x
// +1 for the terminating null byte 
char s[19+1];

// read an integer
scanf("%d", &a);

// store the integer value as a string in s
sprintf(s, "%d", a);
inta;
//[log(2^63-1)]+1=19,其中

//[x]是最大整数您应该使用
sprintf
而不是
itoa
,因为它不是标准

int aInt;
scanf("%d", &aInt)
char str[50];
sprintf(str, "%d", aInt);

itoa的详细使用不是标准功能
sprintf
snprintf
会更好。可能会溢出
s
,我强烈建议使用
snprintf
。谁说你将来不会升级编译器并得到64位int呢?@MattMcNabb更新了答案。是的,
snprintf
是一个更安全的选择。