C语言 如何在C中将字符串类型转换为整数并将其存储在整数数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2922840/
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
how to type cast a string into integer in C and store it in the integer array?
提问by Hick
I want to know how to type cast a string into integer , and not use sprintf() in C
我想知道如何将字符串转换为整数,而不是在 C 中使用 sprintf()
回答by Kevin Le - Khnle
There's no such thing as a string data type in C. But to your question, you can use int atoi ( const char * str )and remember to include <stdlib.h>
C 中没有字符串数据类型这样的东西。但是对于您的问题,您可以使用int atoi ( const char * str )并记住包含<stdlib.h>
回答by progrmr
C doesn't have strings but it does have char arrays (which we often call strings), such as:
C 没有字符串,但它有字符数组(我们通常称之为字符串),例如:
char someChars[] = "12345";
You can convert (not the same as type cast) the contents of the character array to an int like this:
您可以像这样将字符数组的内容转换(与类型转换不同)为 int:
int result;
sscanf(someChars, "%d", &result);
Or using atoi:
或者使用 atoi:
int result = atoi( someChars );
Type casting is like taking a bottle of Coke and putting a Pepsi label on the bottle.
Type conversion is like pouring a bottle of Coke into an Pepsi can. Maybe it will fit.
类型转换就像拿一瓶可乐并在瓶子上贴上百事可乐标签。
类型转换就像将一瓶可乐倒入百事可乐罐中。也许它会适合。
回答by Timo Geusch
You can't cast a char array/const char * into an integer in C, at least not in a way that gives you a sensible integer result[1]. The only exception is if you use it to convert a single char into an integer, which is basically just widening it if you look at the bit representation.
您不能将 char 数组/const char * 转换为 C 中的整数,至少不能以提供合理整数结果的方式[1]。唯一的例外是如果您使用它来将单个字符转换为整数,如果您查看位表示,这基本上只是将其加宽。
The only way you can do the proper conversion functions like atoior sscanf.
您可以执行正确的转换功能的唯一方法,例如atoi或sscanf。
[1] Yes, I know you can convert a pointer (const char *) into an integer, but that converts the value of the pointer and not the value of the data it points to.
[1] 是的,我知道您可以将指针 (const char *) 转换为整数,但这会转换指针的值而不是它指向的数据的值。

