Using atoi with char

2019-06-19 20:54发布

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);

标签: c atoi
5条回答
Luminary・发光体
2楼-- · 2019-06-19 21:30

How about:

   char arr[] = "X";
   int x;
   arr[0] = '9';
   x = atoi(arr);
   printf("%d",x);
查看更多
不美不萌又怎样
3楼-- · 2019-06-19 21:31

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);
查看更多
\"骚年 ilove
4楼-- · 2019-06-19 21:36

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);
查看更多
Rolldiameter
5楼-- · 2019-06-19 21:42

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.

查看更多
干净又极端
6楼-- · 2019-06-19 21:45
char c = '1';
int x = c - '0';
printf("%d",x);
查看更多
登录 后发表回答