【问题标题】:Read file - line by line to create permutations in c逐行读取文件以在 c 中创建排列
【发布时间】:2017-05-30 01:16:45
【问题描述】:

所以我在尝试读取包含三行的文本文件时遇到问题。我正在尝试阅读每一行并为每行创建排列。我想继续循环对每一行执行此操作,直到遇到 EOF。我正在尝试在我的 main 的 while 循环中实现 fgets。我在正确的轨道上吗?我遇到的主要问题是在我的 main 中将一个 char 传递给我的排列方法。

#include <stdio.h>

void swap(char *x, char *y)
{
    char tempVariable;

    tempVariable = *x;
    *x = *y;
    *y = tempVariable;
}

void stringPermutation(char *a, int zeroVariable, int factorial)
{
    int i;

    if(zeroVariable == factorial)
    {
        printf("%s\n", a);
    }
    else
    {
        for(i = zeroVariable; i <= factorial; i++)
        {
            swap((a + zeroVariable), (a + i));
            stringPermutation(a, zeroVariable + 1, factorial);
            swap((a + zeroVariable), (a + i));
            }
        }
    }

int main(int argc, char *argv[])
    {
    if(argc != 2)
    {       
        printf("ERROR - WRONG AMOUNT OF ARGUMENTS\n");

    }
     else
    {   
        FILE *file = fopen(argv[1], "r");
        int x;

        printf("PERMUTATIONS:\n");

        while((x = fgetc(file)) != EOF)
        {   
            stringPermutation(x, 0, x - 1); //I'm messing up here
        }
        fclose(file);
    }
    return 0;
}

【问题讨论】:

  • 好吧,你传递了一个 char ,其中应该是 char* 。你的编译器应该告诉你...
  • 我知道 int x 被传递到一个需要是字符的参数中......我想我的问题是......我如何把那个 int 变成一个字符?投吗?我一直在阅读 fgets 逐行读取,但是,它停在 \n 或 EOF ..?
  • 试试char x[] = "abc"; stringPermutation(x, 0, stelen(x)-1);
  • 感谢 BLUEPIXY 的提示...我可以看到它是如何工作的,但是如果我需要从文件中读取而不是像您那样硬编码呢?
  • char x[256]; while(fgets(x, sizeof x, file)){ x[strcspn(x, "\n")]=0; stringPermutation(x, 0, strlen(x)-1); }

标签: c io permutation


【解决方案1】:

stringPermutation() 期待 char* 而不是 charint。 您正在传递char。看起来stringPermutation 也将参数用作char*,所以在这种情况下调用者是错误的。

看起来您需要将一些字符读入缓冲区并将缓冲区传递给stringPermutation()。更简单地使用fgetsgetline 等在一次调用中读取字符串,而不是自己逐个字符地构建它。

【讨论】:

  • 感谢您抽出宝贵时间帮助我。我会试试你说的,看看是否有效
【解决方案2】:
stringPermutation(x, 0, x - 1);

xint 类型,获取char 的ASCII 码作为值,但函数stringPermutation 需要char *a

我建议使用fgets 来读取文件的行数。

【讨论】:

  • 我觉得我需要使用 fgets...谢谢
猜你喜欢
  • 2013-07-20
  • 2022-01-25
  • 2010-12-24
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 2012-06-13
相关资源
最近更新 更多