【问题标题】:Programming in C write to file [closed]用C编程写入文件[关闭]
【发布时间】:2016-01-09 15:06:26
【问题描述】:

我需要创建一个模拟彩票的程序。我已经生成了开奖号码和彩票,还让用户输入了奖金。我的问题是,如何将门票打印到记事本文件中?我已经用谷歌搜索了几个小时,找不到任何东西。附件是我到目前为止所做的代码。提前致谢。

int draw = 4, i, money;   //for drawn numbers and prize money
int n = 5, j, x, y = 10;  //for generating tickets
bool arr[100] = { 0 };
time_t t;

printf("The Prize money to be won is $ ");
scanf_s("%d", &money);
printf("\n\nThe 4 drawn Numbers are: \n");
srand((unsigned)time(&t));
for (i = 0; i < draw; ++i)
{
    int r = rand() % 25;
    if (!arr[r])
        printf("%3d  ", r + 1);
}
printf("\n");
// generate tickets
printf("\n\nThe tickets are:\n");
srand((unsigned)time(&t));
for (x = 0; x < y; ++x)
{
    for (j = 0; j < n; ++j)
    {
        int r = rand() % 25;
        if (!arr[r])
            printf("%3d  ", r + 1);
    }
    printf("\n");
}

return 0;

【问题讨论】:

  • 检查scanf() 是否为scanf_s("%d", &amp;money); 返回1
  • 哦,没有记事本文件,你要的是文本文件
  • Write to .txt file?的可能重复
  • notepad 文件只不过是一个文本文件,没有特殊格式。
  • 希望贴出的代码在main()函数内,并且该函数以#include &lt;stdio.h&gt;#include &lt;stdlib.h&gt;为前缀

标签: c


【解决方案1】:

printf(...) 函数是fprintf(stdout, ...) 的快捷方式,其中stdout 只是系统标准输出 的文件流,您可以使用fopen() 打开文件,然后fprintf()给它,像这样

FILE *file = fopen("lotery.txt", "w"); // "w" will overwrite the file if exists
if (file == NULL)
    return -1; // failure openning the file

然后,将所有 printf(...) 实例更改为

fprintf(file, ...);

注意:Windows 会抱怨 fopen() 不安全,有一个宏可以关闭这些警告,使用它。不要使用 fopen_s()scanf_s() 编写不可移植的代码,除非您真的只想在这种情况下支持 Windows,而是使用它建议的函数。

【讨论】:

    【解决方案2】:

    建议:

    打开一个输出文件:

    FILE *fp = fopen( "outputFileName", "w");
    if( NULL == fp )
    { // then fopen failed
        perror( "fopen for outputFileName for write failed");
        exit( EXIT_FAILURE );
    }
    

    然后使用fprintf() 将数据输出到文件中。在代码当前调用printf()的每个地方之后调用fprintf()函数;

    在程序结束时,在退出程序之前。

    fclose( fp );
    

    注意:srand() 函数只能在程序顶部附近调用一次,之后调用rand() 来实际获取随机数

    这种线:

    srand((unsigned)time(&t));
    

    最好写成:

    srand((unsigned)time(NULL));
    

    然后可以消除t变量

    为了便于我们人类理解,请遵循公理:每行只有一个语句,并且(最多)每个语句一个变量声明

    建议始终检查对 scanf() 系列函数的任何调用的返回值(而不是参数值),以确保操作成功。

    【讨论】:

    • 为了让我们人类易于理解 -> 通过对人类的理解来帮助我们
    • @iharob,你想说什么?
    • 你使用了尤达条件,尤达说话就像相反!如果你很难理解我在说什么,那么现在你知道为什么if (NULL == fp) 不好了。
    猜你喜欢
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    相关资源
    最近更新 更多