【问题标题】:printing c console output to txt file将 c 控制台输出打印到 txt 文件
【发布时间】:2021-06-20 21:31:56
【问题描述】:

我需要一些有关此 C 代码的帮助。我对C一无所知,我刚开始学习C++,这绝对不是我的代码,我从stackoverflow获得了所有代码。无论如何,该程序运行良好,但有一些错误,程序运行平稳并提供所需的控制台输出。但我不希望它打印到控制台我希望它将所有控制台输出写入 .txt 文件。我没有C代码经验,所以你能帮帮我。这是代码

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

/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int l, int r)
{
   int i;
   if (l != r)
   {
       for (i = l; i <= r; i++)
           {
              swap((a+l), (a+i));
              permute(a, l+1, r);
              swap((a+l), (a+i)); //backtrack
           }
   }
   else
   {
       fp = fopen ("C:\Users\vidit\\Documents\\CODE\\CODE\\C++\\wrds.txt","w");
       fprintf(fp, "%s\n", a);
   }
}

/* arr[]  ---> Input Array
   data[] ---> Temporary array to store current combination
   start & end ---> Staring and Ending indexes in arr[]
   index  ---> Current index in data[]
   r ---> Size of a combination to be printed */
void combinationUtil(char alphas[], char data[], int start, int end,
                     int index, int count)
{
    int i;
    if (index == count)
    {
        data[count] = '\0';
        permute(data, 0, count-1);
        return;
    }

    for (i=start; i<=end && end-i+1 >= count-index; i++)
    {
        data[index] = alphas[i];
        combinationUtil(alphas, data, i+1, end, index+1, count);
    }
}

// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
void printCombination(char alphas[], int n, int count)
{
    int data[count+1];
    combinationUtil(alphas, data, 0, n-1, 0, count);
}

int main()
{
    fp = fopen ("C:\Users\vidit\\Documents\\CODE\\CODE\\C++\\wrds.txt","w");
    char alphas[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Provide here the characters which you wants to use
    int i;
    int len = strlen(alphas);
    for(i = 0; i<len; i++)
        printCombination(alphas, len, i+1);
    fclose (fp);
    return 0;
}

解决方案和解释都会非常有帮助。 控制台输出需要很长时间。

【问题讨论】:

  • 如果你刚开始学习 C++,看 C 代码不是一个好主意。它们是非常不同的语言,以非常不同的方式来做基本的事情。 C++ 已经有一个std::swap 函数,您可以使用std::next_permutation 打印字符串的排列。说到这,C++ 通常使用std::string 而不是char *s。
  • fopen ("C:\Users\vidit\\Docu... 在 C 和 C++ 中,您必须转义所有 `` 字符,而不仅仅是其中的几个

标签: c console


【解决方案1】:

看看这段代码

freopen("wrds.txt", "w", 标准输出);

您可以将控制台重定向到文件:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-04
    • 2021-06-05
    • 2020-04-24
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多