码迷,mamicode.com
首页 > 其他好文 > 详细

itoa/atoi/getpass

时间:2015-04-02 22:38:49      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

myitoa

#include <stdio.h>
#include <string.h>
void resver(char *s)//反转字符串
{
    int len = strlen(s);
    //printf("len=%d\n",len);
    int i = 0;
    char tmp = 0;
    for (; i<len/2; i++)
    {
        tmp = s[i];
        s[i] = s[len-1-i];
        s[len-1-i] = tmp;
    }
}
const char *myitoa(int n)
{
    static char buf[100];//必须为static,或者是全局变量
    memset(buf, 0, sizeof(buf));
    int FlagF = 0;    //1-f, 0-z
    int i = 0;
    if (n < 0)
    {
        FlagF = 1;
        n = 0 - n;
    }
    while (n)
    {
        buf[i++] = n % 10 + '0';
        n = n / 10;
    }
    if (FlagF == 1)
    {
        buf[i++] = '-';
    }
    buf[i] = '\0';
    printf("before buf:%s\n", buf);
    resver(buf);
    printf("after buf:%s\n", buf);
    return buf;
}
int main()
{
    printf("%s\n", myitoa(123));
    printf("%s\n", myitoa(-123));
    return 0;
}

myatoi

#include <stdio.h>
int mystrlen(const char *s)
{
    int i = 0;
    while (*s++)
    {
        i++;
    }
    return i;
}
int power10(int n)
{
    if (n == 0)
    {
        return 1;
    }
    int val = 1;
    int i = 0;
    for (; i < n; i++)
    {
        val = val * 10;
    }
    return val;
}
int char2i(char c)
{
    if ((c >= '0') || (c <= '9'))
    {
        return (c - '0');
    } else
    {
        return 0;
    }
}
int myatoi(const char *str)
{
    int FlagF = 0; //1-f, 0-z
    const char *p = str;
    int i = 0;
    int value = 0;
    if (str[0] == '-')
    {
        FlagF = 1; //
        p = ++str;
    }
    int len = mystrlen(p);
    int lentmp = len;
    for (; i < len; i++)
    {
        value += char2i(p[i]) * power10(lentmp - 1);
        lentmp--;
    }
    if (FlagF == 1)
    {
        return (0 - value);
    } else
    {
        return value;
    }
}
int main()
{
    const char *s = "-123";
    printf("%d\n", myatoi(s));
    return 0;
}

getpass屏幕不回显

技术分享


itoa/atoi/getpass

标签:

原文地址:http://blog.csdn.net/waldmer/article/details/44565009

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!