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

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

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

/*
    本任务为编写一个函数,倒序排放字符串数组。。
     解题思路很简单,两个指针,分别指向头尾。。。然后相性运动,替换值,直到中间。
*/

#include<stdio.h>
#include<string.h>

#define o 50

void turn(char * s1, char * s2, int length);

int main(void)
{
	int i = 0;
	int length = 0;
	char quit = 0;
	char name[50] = {};

	while(quit != 'q')
	{
		printf("Please input: \n");
		fgets(name, o, stdin);
		
		// 善后处理:替换换行符与清空输入缓存区。
		while(name[i] != '\n' && name[i] != '\0')
		{
			i++;
		}
		if(name[i] == '\n')
		{
			name[i] = '\0';
		}
		fflush(stdin);

		length = strlen(name);

		turn(name, name+length-1, length );

		printf("This is the result: \n");
		i = 0;
		while(i <= length)
		{
			printf("%c", name[i]);
			i++;
		}

		printf("\nDo you want to continue??????\nYes or quit :");
		quit = getchar();
		fflush(stdin);
	}

	printf("Bye ~\n");
	getchar();

	return 0;
}

void turn(char * s1, char * s2, int length)
{
	int i = 0;
	char temporary = 0;

	while(i < length/2 )
	{
		temporary = *s1;
		*s1 = *s2;
		*s2 = temporary;

		s1++;
		s2--;
		i++;
	}

	return;
}

猜你喜欢

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