问题描述
- 怎么把数字变成字符串比如已经存在的123要变成字符串要怎么写
-
比如这串代码:
#include
#include
#include
int main( )
{
char a[10000];
int i,j,n,s;
ges(a);
n=strlen(a);
for(i=0;i<n;i++)
{
s+=a[i];
}
我要把得到的s变成字符串?求帮帮忙。
解决方案
使用 sprintf 函数即可。
#include <stdio.h>
void main( void )
{
char buffer[200], s[] = "computer", c = 'l';
int i = 35, j;
float fp = 1.7320534f;
/* Format and print various data: */
j = sprintf( buffer, "tString: %sn", s );
j += sprintf( buffer + j, "tCharacter: %cn", c );
j += sprintf( buffer + j, "tInteger: %dn", i );
j += sprintf( buffer + j, "tReal: %fn", fp );
printf( "Output:n%sncharacter count = %dn", buffer, j );
}
Output
Output:
String: computer
Character: l
Integer: 35
Real: 1.732053
character count = 71
解决方案二:
使用 _itoa_s 函数也可以
#include <stdlib.h>
#include <string.h>
int main( void )
{
char buffer[65];
int r;
for( r=10; r>=2; --r )
{
_itoa_s( -1, buffer, 65, r );
printf( "base %d: %s (%d chars)n", r, buffer, strnlen(buffer, _countof(buffer)) );
}
printf( "n" );
for( r=10; r>=2; --r )
{
_i64toa_s( -1L, buffer, 65, r );
printf( "base %d: %s (%d chars)n", r, buffer, strnlen(buffer, _countof(buffer)) );
}
printf( "n" );
for( r=10; r>=2; --r )
{
_ui64toa_s( 0xffffffffffffffffL, buffer, 65, r );
printf( "base %d: %s (%d chars)n", r, buffer, strnlen(buffer, _countof(buffer)) );
}
}
输出:
base 10: -1 (2 chars)
base 9: 12068657453 (11 chars)
base 8: 37777777777 (11 chars)
base 7: 211301422353 (12 chars)
base 6: 1550104015503 (13 chars)
base 5: 32244002423140 (14 chars)
base 4: 3333333333333333 (16 chars)
base 3: 102002022201221111210 (21 chars)
base 2: 11111111111111111111111111111111 (32 chars)
base 10: -1 (2 chars)
base 9: 145808576354216723756 (21 chars)
base 8: 1777777777777777777777 (22 chars)
base 7: 45012021522523134134601 (23 chars)
base 6: 3520522010102100444244423 (25 chars)
base 5: 2214220303114400424121122430 (28 chars)
base 4: 33333333333333333333333333333333 (32 chars)
base 3: 11112220022122120101211020120210210211220 (41 chars)
base 2: 1111111111111111111111111111111111111111111111111111111111111111 (64 chars)
base 10: 18446744073709551615 (20 chars)
base 9: 145808576354216723756 (21 chars)
base 8: 1777777777777777777777 (22 chars)
base 7: 45012021522523134134601 (23 chars)
base 6: 3520522010102100444244423 (25 chars)
base 5: 2214220303114400424121122430 (28 chars)
base 4: 33333333333333333333333333333333 (32 chars)
base 3: 11112220022122120101211020120210210211220 (41 chars)
base 2: 1111111111111111111111111111111111111111111111111111111111111111 (64 chars)
解决方案三:
http://blog.sina.com.cn/s/blog_616694280100ffv6.html
时间: 2024-09-23 00:32:41