C语言 C char* 到 int 的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13145777/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:14:08  来源:igfitidea点击:

C char* to int conversion

ccharint

提问by Niek

How would I go about converting a two-digit number (type char*) to an int?

我将如何将两位数(类型char*)转换为int

回答by Aamir

atoican do that for you

atoi可以为您做到

Example:

例子:

char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

回答by Omkant

Use atoi() from <stdlib.h>

使用 atoi() 从 <stdlib.h>

http://linux.die.net/man/3/atoi

http://linux.die.net/man/3/atoi

Or, write your own atoi()function which will convert char*to int

或者,编写您自己的atoi()函数,该函数将转换char*int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}