str_to_dec.c

来源:互联网 发布:轻钢房屋设计软件 编辑:程序博客网 时间:2024/06/16 03:19

#include <stdio.h>
#include <string.h>
int str_to_dec(char *s)
{
 int ret = 0;
 int flag;
 if (*s == '-')
 {
  flag = 1;
  s++;
 }
 while (*s)
 {
  if (*s < '0' || *s > '9')
   return 0;
  ret = ret * 10 +(int)(*s -'0');
  s++;
 }
 if (flag == 1)
  ret *= -1;
 return ret;
 

}

int main()
{
 printf("put a string:\n");
 char buf[20];
 fgets(buf, sizeof(buf), stdin);
 buf[strlen(buf) - 1] = '\0';

 int num;
 num = str_to_dec(buf);
 printf("num = %d\n", num);

 return 0;
}