问题描述
在许多种语言中将任何变量都转换为另一种类型非常容易,这为我提供了另一个转换函数的思路,该函数的作用应类似于Python中的str()
。
所以我发现itoa()
是一个将int
变成char * (string)
的函数:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num = 200;
printf("%s",itoa(num));
}
但是事实证明,itoa()
在我的C版本中实际上并不存在,他们声称这是C99:
make_str.c:6:18: error: implicit declaration of function 'itoa' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
printf("%s",itoa(num));
^
make_str.c:6:18: error: format specifies type 'char *' but the argument has type 'int' [-Werror,-Wformat]
printf("%s",itoa(num));
~~ ^~~~~~~~~
%d
尽管我仍然没有关于如何将变量转换为字符串的计划,但我还是去使我的函数改名为make_str()
:
char *make_str(void *var) {
}
问:我还可以使用哪些其他函数将变量更改为字符串?
否,不是浮点值,只有
int
。
解决方法
在C中,char
变量实际上是int。所有char变量都有一个数字值。您可以使用它进行转换。在ASCII中,数字代码如下:
48.'0'
49.'1'
50.'2'
51.'3'
52.'4'
53.'5'
54.'6'
55.'7'
56.'8'
57.'9'
例如,int 48表示char'0'。因此,您可以使用以下代码:
#include <stdio.h>
#include <math.h>
int main(void) {
int entry,copy,count,dividing = 1,size = 0;
char IntToChar[50];
printf("Enter an integer: ");
scanf("%d",& entry);
copy = entry;
if (copy != 0) {
while (copy != 0) {
++size; /*to calculate how many number entry has*/
copy /= 10; /*for example,if you divide 17(for int,not float) to 10,the result is 1*/
}
} else
size = 1; /*possibility of entry to be 0*/
for (count = 0; count < (size - 1); ++count)
dividing *= 10;
copy = entry; /*assignment again*/
for (count = 0; count < size; ++count) {
IntToChar[count] = '0' + (copy / dividing);
copy %= dividing;
dividing /= 10;
}
IntToChar[count] = '\0'; /*adding end of string*/
printf("%s",IntToChar);
return 0;
}
例如,条目是913。因此,大小将是3,划分将是100。如果我们划分副本划分为除,结果为9。如果我们将这9与48('0')相加,则得出57('9')。之后, copy% = dividing 为13,如果将13除以10,则为1,将1,与48('0')相加,结果为49('1'),依此类推,希望对您有所帮助