《c程序设计语言》读书笔记-5.6-指针重写getline等函数

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <curses.h>

int getline_(char *s,int n)
{
    char c;
    char *sta = s;

    while(--n > 0 && (c = getchar()) != EOF && c != '\n')
    {
        *s++ = c;
    }
    if(c == '\n')
        *s++ = c;
    *s = '\0';
    return s - sta;
}

int atoi_(char *s)
{
    int n,sign;

    for(;isspace(*s);s++)
        ;
    sign = (*s == '-') ? -1 : 1;
    if(*s == '+' || *s == '-')
        s++;
    for(n = 0;isdigit(*s);s++)
        n = 10 * n + *s - '0';

    return sign * n;
}

void reverse_(char *s)
{
    int temp;
    char *t;

    for(t = s + strlen(s) - 1;s < t;s++,t--)
    {
        temp = *s;
        *s = *t;
        *t = temp;
    }
}

void itoa_(int n,char *s)
{
    int sign;
    char *t = s;

    if((sign = n) < 0)
        n = -n;
    do
    {
        *s++ = n % 10 + '0';
    }while((n /= 10) != 0);

    if(sign < 0)
        *s++ ='-';
    *s = '\0';
    reverse_(t);

}

int strindex_(char *s,char *t)   //返回最右边出现的位置
{
    char *sta = s;
    char *p,*r;
    int n = -2;

    for(;*s != '\0';s++)
    {
        for(p = s,r = t;*r != '\0' && *p == *r;p++,r++)
            ;
        if(r > t && *r == '\0')
            n =  s - sta;
    }
    if(n != -2)
        return n;
    else
        return -1;
}


int main()
{
    char p[] = "abcdefgab",q[] = "uh";
    int n;
    n = strindex_(p,q);

    printf("%d",n);

    return 0;

}


posted @ 2014-11-14 10:20  司空格子Ored  阅读(406)  评论(0编辑  收藏  举报