《算法竞赛入门经典》——重新实现库函数

在学习字符串时,重新实现一些库函数的功能是很有益的。

练习1:只用getchar函数读入一个整数。假设它占据单独的一行,读到行末为止,包括换行符。输入保证读入的整数可以保存在int中。

// 3.4.4-1 只用getchar函数读入一个整数。

#include <stdio.h>
int main(void)
{
    int a[100], i = 0, num = 0;
    while((a[i] = getchar()) && a[i] != '\n')
    {
        num = num*10 + a[i] - '0';
        i++;
    }
    printf("%d\n", num);
    return 0;
}
练习2:只用fgets函数读入一个整数。假设它占据单独的一行,读到行末为止,包括换行符。输入保证读入的整数可以保存在int中。

// 3.4.4-2 只用fgets函数读入一个整数。

#include <stdio.h>
#include <string.h>
int main(void)
{
	int i, num = 0;
	char s[100];
	fgets(s, sizeof(s), stdin);
	for(i = 0; i < strlen(s)-1; i++)
		num = num*10 + s[i] - '0';
	printf("%d\n", num);
	return 0;
}
练习3:只用getchar实现fgets的功能,即用每次一个字符的方式读取整行。

// 3.4.4-3 只用getchar实现fgets的功能。

#include <stdio.h>
int main(void)
{
	char s[100];
	int i = 0;
	while((s[i] = getchar()) && s[i] != '\n')
	{
		i++;
	}
	s[i] = '\0';
	printf("%s\n", s);
	return 0;
}
练习4:实现strchr的功能,即在一个字符串中查找一个字符。

// 3.4.4-4 实现strchr的功能,即在一个字符串中查找一个字符。

#include <stdio.h>
char * fun(char * s, char c);
int main(void)
{

	return 0;
}

char * fun(char * s, char c)
{
	while(*s && *s != c)
		s++;
	if(*s == c)
		return s;
	else
		return NULL;
}


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值