练习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;
}
posted on 2014-07-19 15:59  lipching  阅读(245)  评论(0编辑  收藏  举报