【问题标题】:Transfer results to txt file C将结果传输到 txt 文件 C
【发布时间】:2015-12-25 01:30:52
【问题描述】:

所以我对编程完全陌生(我已经学习了 3 天),我发现自己遇到了一个我根本不知道如何解决的问题。 我希望这个程序给我从 0 到以 36 为基数的特定数字的每一个组合。当数字只有大约 50000 左右时,这很容易。但我的目标是提取实际单词(也包含数字),如果我尝试获取 5 个字符的单词,终端将开始覆盖前面的单词(没有帮助,我想要所有单词)。 所以我想我应该寻找一种将所有内容传输到 txt 文件中的方法,并且存在我的问题:我不知道如何......对不起,很长的文字,但我想准确地解释我想要得到的东西。感谢您的帮助。

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);
}

【问题讨论】:

  • 如果您使用终端运行您的应用程序,您可以将输出重定向到文件。例如,如果您的可执行文件名为myexe 而不是运行myexe(或./myexe),请使用myexe &gt; outfile.txt(或./myexe &gt; outfile.txt

标签: c file combinations word


【解决方案1】:

一些可能有帮助的观察:

首先是type 相关: 在您的声明中,您创建以下内容:

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

然后你再做分配:

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

虽然 rint 类型,range(通常)为 –2,147,483,648 到 2,147,483,647,
val[i] 是 @ 类型987654331@,范围(通常)仅为 –128 到 127。

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

@Nasim 已经正确解决了另一个问题。使用printf()file 版本 - 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

【讨论】:

    【解决方案2】:

    创建一个文件,然后您可以使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      相关资源
      最近更新 更多