2015-12-25 88 views
0

所以我完全是新的编程(我已经学习了3天),我发现自己面前的问题,我根本不知道如何解决。 我希望这个程序能够给我从0到基数36中的一个特定数字的每一个组合。当数字只有大约50000时,这很容易。但是我的目标是提取真实的单词(也有数字),如果我试图获得5个字符的单词,终端将开始覆盖以前的单词(没有帮助,我希望所有单词都有)。 所以我认为我应该寻找一种方法来将所有内容传输到一个txt文件中,并且存在我的问题:我不知道如何...对于长文本抱歉,但我想解释我正在试图获得什么。谢谢您的帮助。传输结果到txt文件C

int main() { 
    int dec, j, i, q, r, k; 
    char val[80]; 
    printf("Enter a decimal number: "); 
    scanf("%d", &dec); 
    for (k = 0; k <= dec; k++) { /*repeat for all possible combinations*/ 
     q = k; 
     for (i = 1; q != 0; i++) { /*convert decimal number to value for base 36*/ 
      r = q % 36; 
      if (r < 10) 
       r = r + 48; 
      else 
       r = r + 55; 
      val[i] = r; 
      q = q/36; 
     } 
     for (j = i - 1; j > 0; j--) { /*print every single value*/ 
      printf("%c", val[j]); 
     } 
     printf(" ");  /*add spaces because why not*/ 
    } 
    return (0); 
} 
+1

如果您使用终端来运行您的应用程序,您可以将输出重定向到一个文件。例如,如果您的可执行文件命名为'myexe'而不是运行'myexe'(或'。/ myexe'),请使用'myexe> outfile.txt'(或'./myexe> outfile.txt') – orestisf

回答

0

的实地观测可能求助:

首先是type相关: 在你的声明,你创建以下文件:

int dec, j, i, q, r, k; 
char val[80]; 

然后后来又使分配:

val[i] = r;//assigning an int to a char, dangerous 

虽然r是具有-2147483648〜2,147,483,647一个range(典型地)类型int
val[i]char类型的具有一定范围(通常)只有-128到127.

因此,您可能会遇到溢出,导致意外的结果。 最直接的解决方案是对这两个变量使用相同的类型。选择intchar,但不是两者。

另一个已由@Nasim正确解决。使用file版本printf() - fprintf()。作为链接所示,原型fprintf()是:

int fprintf(FILE *stream, const char *format [, argument ]...); 

用例:

FILE *fp = fopen(".\somefile.txt", "w");//create a pointer to a FILE 
if(fp)//if the FILE was successfully created, write to it... 
{ 
    // some of your previous code... 
    for (j = i - 1; j > 0; j--) 
    { /*print every single value*/ 
      fprintf(fp, "%c", val[j]);//if val is typed as char 
      //OR    
      fprintf(fp, "%d", val[j]);//if val is typed as int 
    } 
    fclose(fp); 
} 

最后,有各种各样的方法来执行基本转换。有些more complicatedothers

0

创建一个文件,然后你可以使用fprintf中()代替了printf两者之间唯一的区别是,你需要指定文件作为参数

FILE *myFile = fopen("file.txt", "w"); //"w" erase previous content, "a" appends 
If(myFile == NULL) {printf("Error in openning file\n"); exit(1);} 
fprintf(myFile, "some integer : %d\n", myInteger); // same as printf my specify file pointer name in first argument 
fclose(myFile); //dont forget to close the file