重新實現庫函數

來源:互聯網
上載者:User

標籤:style   blog   color   檔案   width   io   

練習1:只用getchar函數讀入一個整數。假設它佔據單獨的一行,讀到行末為止,包括分行符號。輸入保證讀入的整數可以儲存在int中。

代碼:

 

//改進方案  3.4.4-1 只用getchar函數讀入一個整數。#include <stdio.h> int main(){    int c;    int n=0;    while ((c=getchar())!=‘\n‘)    {        n=n*10+c-‘0‘;    }    printf("%d",n);    return 0;}

 

 

 

 

#include<stdio.h>int main(){    int sum,a[100],i;    i=0;    sum=0;    while((a[i]=getchar())&&a[i]!=‘\n‘)    {        sum=sum*10+a[i]-‘0‘;        i++;    }    printf("%d\n",sum);    return 0;}

 

練習2:只用fgets函數讀入一個整數。假設它佔據單獨的一行,讀到行末為止,包括分行符號。輸入保證讀入的整數可以儲存在int中。

代碼:

//讀入的字串中最後包含讀到的分行符號。因此,確切地說,調用fgets函數時,最多隻能讀入n-1個字元。//讀入結束後,系統將自動在最後加‘\0‘,並以str作為函數值返回。//函數原型是:char *fgets(char *s, int n, FILE *stream);//stdin(Standardinput)標準輸入#include<stdio.h>#include<string.h>int main(){    int i,num=0;    char s[100];    fgets(s,strlen(s),stdin);//stdin表示用的不是指定檔案的內容 而是自己輸入的內容     for(i=0;i<strlen(s)-1;i++)    {        num=num*10+s[i]-‘0‘;    }    printf("%d\n",num);    return 0;}

 

 

 

練習3:只用getchar實現fgets的功能,即用每次一個字元的方式讀取整行。

代碼:

#include<stdio.h>int main(){    int i;    char s[100];    i=0;    while((s[i]=getchar())&&s[i]!=‘\n‘)    {        i++;    }     s[i]=‘\0‘;    printf("%s\n",s);    return 0;}

 

//另一種方法,練習3隻用getchar實現fgets的功能,即用每次一個字元的方式讀取整行。#include<stdio.h>int main(){    char c;    while((c=getchar())!=‘\n‘)    {        printf("%c",c);    }    return 0;}

 

練習4:實現strchr的功能,即在一個字串中尋找一個字元。(注:不一定要用到strchr 只是需要得到相同的結果而已 )

char *strchr(const char* _Str,int _Val)
char *strchr(char* _Str,int _Ch)
標頭檔:#include <string.h>
功能:尋找字串s中首次出現字元c的位置
說明:返回首次出現c的位置的指標,返回的地址是字串在記憶體中隨機分配的地址再加上你所搜尋的字元在字串位置,
如果s中不存在c則返回NULL。
傳回值:成功則返回要尋找字元第一次出現的位置,失敗返回NULL

代碼:

 

#include<stdio.h>#include<string.h>int main(){    char str[]="This is a sample string.";    int i;    for(i=0;i<strlen(str);i++)    {        if(str[i]==‘s‘)        {            printf("found at %d\n",i+1);        }    }    return 0;}

 

 

練習5 實現isalpha和isdigit的功能,即判斷字元是否為字母/數字 

代碼:

 

#include<stdio.h>int main(){    char c;    while((c=getchar())!=NULL)    {        if( (c>=‘a‘ && c<=‘z‘) || (c>=‘A‘ && c<=‘Z‘))        {            printf("Character %c is alphabetic.\n",c);        }        if(c>=‘0‘ && c<=‘9‘)        {            printf("Character %c is digit.\n",c);        }    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.