C 使用程序的输出作为同一程序的输入
我正在写一个程序来生成给定数列的所有可能的排列,然后从这些排列中生成所有可能的二叉树,所以我认为有一个程序可以生成排列,并将结果存储到一个文件中,然后编写进一步的代码来逐行读取(其中包含所有排列)然后用它们生成二叉树,现在我已经写了半个程序来生成排列,并将结果存储在文件中C 使用程序的输出作为同一程序的输入,c,algorithm,file,permutation,C,Algorithm,File,Permutation,我正在写一个程序来生成给定数列的所有可能的排列,然后从这些排列中生成所有可能的二叉树,所以我认为有一个程序可以生成排列,并将结果存储到一个文件中,然后编写进一步的代码来逐行读取(其中包含所有排列)然后用它们生成二叉树,现在我已经写了半个程序来生成排列,并将结果存储在文件中 #include <stdio.h> //function to print the array void printarray(int arr[], int size) { FILE *fp;
#include <stdio.h>
//function to print the array
void printarray(int arr[], int size)
{
FILE *fp;
int i,j;
fp=fopen("result.txt","w");
for(i=0; i<size; i++)
{
// printf("%d\t",arr[i]);
fprintf(fp,"%d\t",arr[i]);
}
printf("\n");
fclose(fp);
}
//function to swap the variables
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
//permutation function
void permutation(int *arr, int start, int end)
{
if(start==end)
{
printarray(arr, end+1);
return;
}
int i;
for(i=start;i<=end;i++)
{
//swapping numbers
swap((arr+i), (arr+start));
//fixing one first digit
//and calling permutation on
//the rest of the digits
permutation(arr, start+1, end);
swap((arr+i), (arr+start));
}
}
int main()
{
//taking input to the array
int size;
printf("Enter the size of array\n");
scanf("%d",&size);
int i;
int arr[size];
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
//calling permutation function
permutation(arr, 0, size-1);
return 0;
}
#包括
//函数打印数组
void printary(int arr[],int size)
{
文件*fp;
int i,j;
fp=fopen(“result.txt”,“w”);
对于(i=0;i您的fopen(“result.txt”,“w”);
每次打开时都会截断文件。
使用fopen(“result.txt”,“a”)
代替包含
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#define N 10
void print(int *num, int n)
{
FILE *fp;
fp=fopen("result.txt","a");
int i;
for ( i = 0 ; i < n ; i++)
// printf("%d ", num[i]);
fprintf(fp,"%d ",num[i]);
fprintf(fp,"\n");
fclose(fp);
}
int main()
{
int num[N];
int *ptr;
int temp;
int i, n, j;
printf("\nHow many number you want to enter: ");
scanf("%d", &n);
printf("\nEnter a list of numbers to see all combinations:\n");
for (i = 0 ; i < n; i++)
scanf("%d", &num[i]);
for (j = 1; j <= n; j++) {
for (i = 0; i < n-1; i++) {
temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
print(num, n);
}
}
return 0;
}
#包括
#包括
#定义n10
无效打印(整数*num,整数n)
{
文件*fp;
fp=fopen(“result.txt”,“a”);
int i;
对于(i=0;i 对于(j=1;j是的,我试过了,结果很糟糕,输出文件中有无限循环之类的东西。请不要每次打开文件,写一行,然后再关闭它。这是非常低效的,因为它意味着对于每个排列,您都需要进行(大约三次)操作系统调用。在开始时打开文件,并通过调用传递处理程序,然后将调用写入文件。给人打电话是确保没有人帮助你的可靠方法。请保持礼貌。向下投票意味着有人认为问题不合适或不够好。没有必要如此认真地对待它。至于程序挂起你可以先在调试器中运行它,看看发生了什么。