回答
这应该有助于
#include <stdlib.h>
inline int to_int(const char *s)
{
return atoi(s);
}
以防万一为例用法
int main(int ac, char *av[])
{
printf(" to_int(%s) = %d " ,av[1] , to_int(av[1]));
return 0;
}
- 在该包装中闪烁两次 - – Sebivor
这是最C运行库的一部分:
#include <stdlib>
char *a = "1234";
int i = atoi(a);
这就是atoi
功能。请仔细阅读各种可用的方法。 C的图书馆非常精简,所以不用多久。
['atoi'有害](https://blog.mozilla.org/nnethercote/2009/03/13/atol-considered-harmful/)和[shouldn' (http://stackoverflow.com/q/17710018/995714) –
有几种方法,以一个字符串(在一个char *
指出)转换成int
:
我在这里列出其中的一些:
让我们假设您有一个字符串str
decl ARED为:
char *str = "44221";
INT A =的atoi(STR);
这将返回由str
指向的字符串转换的int
值。虽然方便,但当用户提供无效输入时,此功能不会执行准确的错误报告。使用的sscanf():这类似于通常的
scanf
除了它从一个字符串,而不是从stdin
读取输入。int a; int v = sscanf(str, "%d", &a); // XXX: v should be 1 since 1 conversion is performed; handle the conversion error if it isn't
strtol将:此转换给定的字符串转换为长整型。文档发现在:http://man7.org/linux/man-pages/man3/strtol.3.html
一般用法:
char *ptr; long a = strtol(str, &ptr, base);
第一个无效字符(不是数字)的地址存储在ptr
。基地是默认10
通过迭代字符值:为什么取决于当你可以编写自己的程序来实现这个库?这并不难。这样你甚至可以执行所需的验证/错误检查。
示例代码:
unsigned char ch; int a = 0; // Add checks to see if the 1st char of the string is a '+' or '-'. for (i = 0; i < strlen(str); i++) { ch = str[i]; //Add error checks to see if ch is a digit or not (e.g. using isdigit from <ctype.h>). a = a*10 + (ch - '0'); }
希望这有助于!
- 1. INT转换为char
- 2. 转换类型为int(C :: *)(INT,CHAR)为int类型(INT,CHAR)
- 3. 将int转换为char
- 4. 将char转换为int?
- 5. INT类型转换为char *
- 6. 转换一个int为char *
- 7. INT转换为char *指针
- 8. 将char *转换为int
- 9. 将short int []转换为char *
- 10. int转换为char * C++中
- 11. char不转换为int
- 12. int转换为const char *
- 13. INT为CHAR类型转换
- 14. 将int转换为char
- 15. 将const char *转换为int
- 16. 将int转换为char?
- 17. F# - 将char转换为int
- 18. 将char *转换为int
- 19. 无法从char []转换为int []
- 20. 从'int'无效转换为'const char *'
- 21. 将int转换为char并反转
- 22. 从char *转换为signed char *
- 23. 迭代char *错误没有从char *转换为int
- 24. 为什么Char隐式转换为Int?
- 25. 将int从int转换为char,其中涉及溢出错误
- 26. char从'char *'无效转换为'char'[-fpermissive]
- 27. 从'int'到'char *'的无效转换
- 28. 无效的转换从'int'到'const char *'
- 29. 从int,float,char,double的类型转换
- 30. 从一个int到char的转换
''343''不是字符串 –