C语言 将 atoi 与 char 一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2915725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using atoi with char
提问by John Doe
Is there a way of converting a char into a string in C?
有没有办法在 C 中将字符转换为字符串?
I'm trying to do so like this:
我正在尝试这样做:
char *array;
array[0] = '1';
int x = atoi(array);
printf("%d",x);
采纳答案by Jacob
How about:
怎么样:
char arr[] = "X";
int x;
arr[0] = '9';
x = atoi(arr);
printf("%d",x);
回答by BlueRaja - Danny Pflughoeft
char c = '1';
int x = c - '0';
printf("%d",x);
回答by Platinum Azure
If you're trying to convert a numerical char to an int, just use character arithmetic to subtract the ASCII code:
如果您尝试将数字 char 转换为 int,只需使用字符算术来减去 ASCII 代码:
int x = myChar - '0';
printf("%d\n", x);
回答by Paul Michaels
You need to allocate memory to the string, and then null terminate.
您需要为字符串分配内存,然后空终止。
char *array;
array = malloc(2);
array[0] = '1';
array[1] = 'char array[10];
array = "1";
int x = atoi(array);
printf("%d",x);
';
int x = atoi(array);
printf("%d",x);
Or, easier:
或者,更简单:
char string[2];
string[0] = '1';
string[1] = 0;
回答by Steve Emmerson
You can convert a character to a string via the following:
您可以通过以下方式将字符转换为字符串:
##代码##Strings end with a NUL character, which has the value 0.
字符串以 NUL 字符结尾,其值为 0。

