Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

c - using output of a program as input in same program

I am writing a program to generate all possible permutations of a given series of numbers and then generate all possible binary trees from that permutations so, what I thought is having a program which generates permutations and stores the result to a file and then write further code to read line by line (which has all permutations ) and generate binary trees out of them, so right now I have written half program which generates permutation and it stores the result in file.

#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	",arr[i]);
          fprintf(fp,"%d	",arr[i]);
    }
    printf("
");
    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
");
    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;
}

but the problem here in this program is that this program only stores one permutation and does not stores other permutations in result.txt file, how do I go on storing result this way. Also program does not ends a blank cursor blinking which gives a false impression of infinite while loop. I had to press Ctrl+c to end the program how to get rid of this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

your fopen("result.txt","w"); truncates file each time opened. use fopen("result.txt","a"); instead


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...