【发布时间】: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