简体   繁体   中英

Generating Random Numbers in C and writing it to a text file

I've created a project that reads numbers from a text file and draws an isometric projection of it, but now I'm trying to create a program that generates numbers from 0-9 and writes them in the document. This is what my code looks like, but the document remains empty. I'm under the assumption that the error is either in my rand() function usage, or when I convert the integers to characters.

Thank you in advance for all the input, and I apologize if it's just an operator error. I'm pretty new to this stuff:

#include <stdio.h>
#include <stdlib.h>

int     main(void)
{
    char    str[10];
    FILE    *fptr;
    int     i;
    int     num;
    char    num2;
    i = 0;

    fptr = fopen("map.fdf", "w");
    if (fptr == NULL)
    {
        printf("ERROR Creating File!");
        exit(1);
    }
    while (str[i] != '\0')
    {
        num = rand() % 10;
        num2 = num + '0';
        str[i] = num2;
        i += 1;
    }
    puts(str);
    fprintf(fptr,"%s", str);
    fclose(fptr);
    return (0);
}

I don't understand your while loop, it seems to wait for some condition that it doesn't contain code to make happen.

Anyway, how about not re-inventing how to convert single-digit integers to characters, and instead using higher-level I/O functions to just print to the file? That's why they're there, after all. :)

for (int i = 0; i < 10; ++i)
{
  fprintf(fptr, "%d", rand() % 10);
}
fprintf(fptr, "\n");  /* Probably nice to make it a line. */

If you really must make do without for , you can of course always manually transform it into a while loop:

int i = 0;
while(i++ < 10)
{
  fprintf(fptr, "%d", rand() % 10);
}

您的“str”未初始化,但显然有一个 '\0' 字符作为它的第一个元素,因此 while 循环不会执行。

So I got assignment today in file handling to separate even,odd and prime numbers to different files, I also decided create input file with random numbers. I was also facing similar problem to yours.

FILE *fn;
int num, n, range;

printf("Enter number of positive integer:");
scanf("%d", &n);
printf("Enter max integer:");
scanf("%d", &range);

fn=fopen("number.txt", "w");
for (int i=0; i<n; ++i) {
    num = (rand()%range) + 1;
    fprintf(fn, "%d\n", num);
}
fclose(fn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM