-1

I'm need to create a program that simulates a lottery. I've already generated the drawn numbers and the tickets and also had the user input the prize money. My question is, how can I print the tickets to a notepad file? I've been Googling for hours and can't find anything. Attached is the code I've done so far. Thanks in advance.

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;
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97

2 Answers2

1

The printf(...) function is a shortcut for fprintf(stdout, ...) where stdout is simply the file stream for the standard output of your system, you can open the file with fopen() and then fprintf() to it, like this

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

and then, change all the printf(...) instances to

fprintf(file, ...);

NOTE: Windows will complain about fopen() being unsafe, there is a macro that turns these warnings off, use it. Instead of writing non-portable code using fopen_s() or scanf_s() unless you really want to support Windows only in that case, use the functions that it suggests.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

suggestions:

open a output file:

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

then use fprintf() to output the data to the file. Call the fprintf() function after each place the code is currently calling printf();

at the end of the program, before exiting the program.

fclose( fp );

Note: the srand() function should only be called once, near the top of the program, Thereafter, call rand() to actually get the random numbers

this kind of line:

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

would be better written as:

srand((unsigned)time(NULL));

and then the t variable can be eliminated

for ease of understanding by us humans, please follow the axiom: only one statement per line and (at most) one variable declaration per statement

Suggest to always check the returned value (not the parameter value) from any call to the scanf() family of functions to assure the operation was successful.

user3629249
  • 16,402
  • 1
  • 16
  • 17