C primer plus 第六版 第十一章 第七题 编程练习答案

版权声明:转载请注明来源~ https://blog.csdn.net/Lth_1571138383/article/details/85260340

Github地址: φ(>ω<*)这里这里。

/*
    本次任务是设计一个strncpy(s1,s2,n)这样的函数,名字为 mystrncpy。
     目标字符串不能以空字符结尾,如果第二个参数的长度大于n.原函数如果大于n是不会把s1结尾编程空函数的。
*/

#include<stdio.h>

#define n 20

char *mystrncpy(char * s1, const char * s2,  int o);

int main(void)
{
	char s1[n+n] = {};
	char s2[n+n] = {};
	char quit = 0;

	while(quit != 'q')
	{
		printf("Please input the first string(The limit is 20 character):\n");
		fgets(s1, n, stdin);
		fflush(stdin);
		printf("Please input the second string(The limit is 20 character):\n");
		fgets(s2, n, stdin);
		fflush(stdin);

		mystrncpy(s1, s2, n-1);
		printf("The result with copy is like this:\n");
		fputs(s1, stdout);

		printf("Do you want to quit or continue(Enter 'q' to quit)?  Choies:\n");
		fflush(stdin);
		quit = getchar();
	}

	printf("Bye ~\n");

	getchar();

	return 0;
}

char *mystrncpy(char * s1, const char * s2, int o)
{
	// 我是没见过原strncpy的函数内部具体实现。
	// 这里要完成相应操作,我的思路是:
	// 循环处理,测试条件就是读入字符小于n, 和读到s2的结尾
	// 这样就保证了不溢出,也保证了读入的终点。

	int i = 0;

	// 不过在那样处理之前,我得先找到s1的结尾。
	// 虽然可以用strlen,但是既然不能用 strncpy, 那我就不用string.h头文件!!!!

	while( *s1 != '\n' && *s1 != '\0' )
	{
		// 这里选用换行符是因为 main() 中我用 fgets()函数获取输入了。该函数会保留结尾的换行符。
		// 如果溢出了还会有空字符。。
		s1++;
	}

	while( i < o && *s2 != '\0')
	{
		*s1 = *s2;
		s1++;
		s2++;
	}

	return NULL;
}

猜你喜欢

转载自blog.csdn.net/Lth_1571138383/article/details/85260340