Question

I need to save up to 16 floats to a bin file, to be later read and some things done to the information, but I have a problem from the get go as I'm not too sure what the best method to do this is and what I've written doesn't work

void FileMaker (void)
{
char buff[10];
float num;
int count = 0;
printf("Enter 16 Floating numbers:");
FILE *fh = fopen ("Matrix.bin", "wb");

if (fh == NULL)
printf("Fail");

if (fh != NULL)
    {
        while (count >17)
        {
            fgets(buff, 10, stdin);
            num = atof(buff);
            fwrite(&num, sizeof(float), 1, fh);
            count++;
        }
    fclose (fh);
    }
}

Basically what I've tried to do is one at a time get a float from the keyboard and then print it to the file and repeat 16 times but the program does nothing instead and reaches the return (0) in main without getting anything from the user.

Was it helpful?

Solution

The issue is here:

while (count >17)

the code will not enter the block, because 0 > 17 is false.

try this:

while (count < 17)

(or I personally like more the for loops)

for (count = 0; count < 17; ++count)
{
...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top