您的位置:首页 > 编程语言 > C语言/C++

C/C++ | 18-3 递归反向输出字符串

2017-07-05 10:32 399 查看
递规反向输出字符串的例子,可谓是反序的经典例程

/*
递规反向输出字符串
*/

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <assert.h>

using namespace std;

void inverse(char *p)
{
if (*p == '\0') return;
else
{
inverse(p + 1);//重点
printf("%c", *p);
}
}

int main()
{
char str[] = "!1ab sd9";
inverse(str);

system("pause");
return 0;

}

对于文件操作

/*
递规反向输出字符串
文件为逐行倒叙
*/

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <assert.h>

using namespace std;

void inverse(FILE *fread,FILE*fwrite)
{
char buf[1024] = { 0 };
if (!fgets(buf, sizeof(buf), fread)) return;
inverse(fread, fwrite);
fputs(buf, fwrite);    //仍是循环后输出
}

int main()
{
FILE *fr = NULL;
FILE *fw = NULL;
fopen_s(&fr, "f1.txt", "r");
fopen_s(&fw, "f2.txt", "w");
if (fr == NULL | fw == NULL) return -1;
inverse(fr, fw);
fclose(fr);
fclose(fw);
cout << "Done" << endl;
system("pause");
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: