#include<stdio.h>
#include<string.h>
char *int_to_string( int n );
void main()
{
int n;
printf("Enter the number : ");
scanf("%d",&n);
printf("\n%d in words is : %s.\n",n,int_to_string(n));
}
char *int_to_string( int n)
{
char str[100]="";
if(n<10)
{
switch(n)
{
case 0: return "Zero";
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
case 4: return "Four";
case 5: return "Five";
case 6: return "Six";
case 7: return "Seven";
case 8: return "Eight";
case 9: return "Nine";
}
}
else
{
strcat(str,int_to_string(n/10));
strcat(str," ");
return strcat(str,int_to_string(n%10));
}
}
函数 int_to_string() 应返回一个字符串,其中包含与传递的单词中的数字等效的字符串。对于单位数字(即 0-9 )它工作得很好,但在上面它什么也没有给出。
最佳答案
该函数具有未定义的行为。
它返回一个指向本地数组str
的指针,该数组通常在退出函数后被销毁。
考虑到最好将参数定义为 unsigned int
类型。否则该函数需要检查该数字是否不为负数。
您可以通过声明第二个参数来简化任务,该参数将指定一个以零结尾的字符数组来存储结果字符串。
或者你必须动态分配内存。
这里显示了这两种方法。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * int_to_string( unsigned int n )
{
if( n < 10 )
{
char *p = "";
switch( n )
{
case 0:
p = "Zero";
break;
case 1:
p = "One";
break;
case 2:
p = "Two";
break;
case 3:
p = "Three";
break;
case 4:
p = "Four";
break;
case 5:
p = "Five";
break;
case 6:
p = "Six";
break;
case 7:
p = "Seven";
break;
case 8:
p = "Eight";
break;
case 9:
p = "Nine";
break;
}
char *q = malloc( strlen( p ) + 1 );
strcpy( q, p );
free( p );
return q;
}
else
{
char *q = int_to_string( n / 10 );
char *p = int_to_string( n % 10 );
q = realloc( q, strlen( q ) + strlen( p ) + 2 );
strcat( q, " " );
return strcat( q, p );
}
}
char * int_to_string1( unsigned int n, char *s )
{
if( n < 10 )
{
char *p = "";
switch( n )
{
case 0:
p = "Zero";
break;
case 1:
p = "One";
break;
case 2:
p = "Two";
break;
case 3:
p = "Three";
break;
case 4:
p = "Four";
break;
case 5:
p = "Five";
break;
case 6:
p = "Six";
break;
case 7:
p = "Seven";
break;
case 8:
p = "Eight";
break;
case 9:
p = "Nine";
break;
}
return strcat( s, p );
}
else
{
strcat( int_to_string1( n / 10, s ), " " );
return int_to_string1( n % 10, s );
}
}
int main( void )
{
unsigned int n = 1234567890;
char *s = int_to_string( n );
puts( s );
free( s );
char s1[100];
s1[0] = '\0';
puts( int_to_string1( n, s1 ) );
}
程序输出为
One Two Three Four Five Six Seven Eight Nine Zero
One Two Three Four Five Six Seven Eight Nine Zero
关于c - 不返回字符串。这个程序将 123 这样的数字转换为 "One Two Three"这样的单词,为什么最后我什么也没有得到?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37817181/