[英]Converting an Integer to String (C)
I'm fairly new to c and have been trying to figure out how convert an integer into a string of numbers, and this i what i have so far: 我对c相当陌生,并且一直在尝试弄清楚如何将整数转换为数字字符串,而这是我到目前为止所拥有的:
long long int inputNum = 0;
char str [20];
int len = 0;
printf("Please enter the integer to be converted,\nit should be no more than 10 digits long: \n");
scanf("%d", &inputNum);
sprintf(str,"%d", inputNum);
len = strlen(str);
printf("%d", len);
return 0;
However im encountering an issue were if the int entered is more than 10 characters long the program will still say that the lenght is 10. Im not sure if this is an issue with data types (long long int for example) or if im just implementing the string impoperly. 但是我遇到的一个问题是,如果输入的int长度超过10个字符,则程序仍会说长度是10。我不确定这是否是数据类型的问题(例如long long int)还是我只是在实现字符串不正确。
Your format specifier is wrong. 您的格式说明符有误。
%d
is used for regular int
variables. %d
用于常规int
变量。 Yours is a long long int
. 你的是一个
long long int
。 Use %lld
instead and it should work just fine. 请改用
%lld
,它应该可以正常工作。
Also, you should be aware that exactly how many digits an int
can store is platform-dependant. 另外,您应该注意,
int
可以存储多少位数完全取决于平台。 In your case, it's probably 32 bits, which works out to a range of approx -2^31
to 2^31
. 在您的情况下,它可能是32位,大约在
-2^31
到2^31
的范围内。 Likewise, a long long
is 64 bits long, with analogous constraints. 同样,
long long
为64位长,具有类似的约束。 What I'm saying is that you're going to need a different solution for an arbitrary number of digits. 我的意思是,您需要为任意数量的数字提供不同的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.