Using atoi with char

≯℡__Kan透↙ 提交于 2019-12-23 09:39:07

问题


Is there a way of converting a char into a string in C?

I'm trying to do so like this:

   char *array;

   array[0] = '1';

   int x = atoi(array);

   printf("%d",x);

回答1:


How about:

   char arr[] = "X";
   int x;
   arr[0] = '9';
   x = atoi(arr);
   printf("%d",x);



回答2:


char c = '1';
int x = c - '0';
printf("%d",x);



回答3:


If you're trying to convert a numerical char to an int, just use character arithmetic to subtract the ASCII code:

int x = myChar - '0';
printf("%d\n", x);



回答4:


You need to allocate memory to the string, and then null terminate.

char *array;

array = malloc(2);
array[0] = '1';
array[1] = '\0';

int x = atoi(array);

printf("%d",x);

Or, easier:

char array[10];

array = "1";

int x = atoi(array);

printf("%d",x);



回答5:


You can convert a character to a string via the following:

char string[2];
string[0] = '1';
string[1] = 0;

Strings end with a NUL character, which has the value 0.



来源:https://stackoverflow.com/questions/2915725/using-atoi-with-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!