将 atoi 与 char 一起使用

发布于 2024-09-03 06:19:55 字数 151 浏览 5 评论 0原文

C语言中有没有办法将字符转换为字符串?

我正在尝试这样做:

   char *array;

   array[0] = '1';

   int x = atoi(array);

   printf("%d",x);

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

万劫不复 2024-09-10 06:19:55
char c = '1';
int x = c - '0';
printf("%d",x);
char c = '1';
int x = c - '0';
printf("%d",x);
疏忽 2024-09-10 06:19:55

如果您尝试将数字 char 转换为 int,只需使用字符算术减去 ASCII 代码:

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

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);
烟雨扶苏 2024-09-10 06:19:55

您需要为字符串分配内存,然后以 null 终止。

char *array;

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

int x = atoi(array);

printf("%d",x);

或者,更简单:

char array[10];

array = "1";

int x = atoi(array);

printf("%d",x);

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);
轻许诺言 2024-09-10 06:19:55

怎么样:

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

How about:

   char arr[] = "X";
   int x;
   arr[0] = '9';
   x = atoi(arr);
   printf("%d",x);
似梦非梦 2024-09-10 06:19:55

您可以通过以下方式将字符转换为字符串:

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

字符串以 NUL 字符结尾,其值为 0。

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.

荭秂 2024-09-10 06:19:55

atoi 函数的声明是(它等待一个“字符串”):

int atoi(const char * str)

如果您打算将它与单个字符一起使用,您将得到分段错误,因为该函数尝试读取内存直到找到'\0'

例如试试这个:

char char_digit = '5';
char string_for_atoi[2] = { char_digit, '\0' };

int number = atoi(string_for_atoi);

A declaration of the atoi function is (it awaits a "string"):

int atoi(const char * str)

If you are going to use it with a single character, you will get a segmentation fault, because the function tries to read the memory until it finds the '\0'!

E. g. try this:

char char_digit = '5';
char string_for_atoi[2] = { char_digit, '\0' };

int number = atoi(string_for_atoi);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文