Chinaunix首页 | 论坛 | 博客
  • 博客访问: 169797
  • 博文数量: 49
  • 博客积分: 2802
  • 博客等级: 大尉
  • 技术积分: 502
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-25 12:02
个人简介

来就来吧

文章分类

全部博文(49)

文章存档

2014年(1)

2012年(1)

2011年(11)

2010年(26)

2009年(10)

分类: C/C++

2010-02-09 15:43:44

c语言字符串转换整数

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define bool _Bool
#define true 1
#define false 0
bool strToInt(char *s, long *num)
{
    bool minus = false;
    bool first = true;
    while(*s != '\0'){
        if (*s == '+' && first) {
            s++;
        } else if(*s == '-' && first) {
            minus = true;
            s ++;
        } else {
            first = false;
            if (*s < '0' || *s >'9')
            {
                printf("The string is not Int num\n");
                return false;
            }
            *num = *num *10 + (*s-'0');
            s ++;
        }
    }
    if (minus) {
        *num = 0 - *num;
    }
    return true;
}

int main()
{
    char *s = "-123";
    long num = 0;
    if(strToInt(s, &num)) {
        printf("num = %ld\n", num);
    }
}


实际上,c 语言库中有此函数atoi()
    char *c = "345";
    printf("c = %d\n", atoi(c));
阅读(461) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~