2

I'm having trouble writing an array of double numbers in a text file. The problem is, the code runs, but doesn't write out anything.

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

 int main() {

     FILE *out;
     double numbers[30];
     int i=0;

     for(i;i<30;i++) 
         scanf("%lf", &numbers[i]);

     out=fopen("out.txt", "w");

     if (out == NULL) {

         fprintf(stderr, "error in opening .txt");
         exit(EXIT_FAILURE);
     }

     while ( i<30 ) {

         fprintf(out, "%.3f", numbers[i]);
         i++;
     }

     fclose(out);

     return 0;
 }

Basically, the code is supposed to write out an array of 30 double numbers in a text file, and round the decimals to '.3'.

5
  • Could you please add the tag 'C' ? Commented Mar 21, 2015 at 11:24
  • 3
    You forgot to set i back to zero after the first loop. Commented Mar 21, 2015 at 11:25
  • 1
    Yes add i = 0; in front of while( i < 30 ) Commented Mar 21, 2015 at 11:25
  • 2
    Use a` for` - Better than a while loop in this case. Reset i. Use braces around scanf and check the return value Commented Mar 21, 2015 at 11:28
  • 1
    Wow, um yes it worked, I'm embarassed..... Commented Mar 21, 2015 at 11:28

1 Answer 1

4

You forgot to re-initialise i to 0, hence the current value of i is 30, which effectively causes the while loop to not execute.

 i = 0; //Re-initialise i.
 while ( i<30 ) {

         fprintf(out, "%.3f", numbers[i]);
         i++;
     }

It would be better, if you use a for loop, as it's syntax helps you to remember to initialise the increment variable.

for (i = 0; i < 30; ++i)
     fprintf(out, "%.3f", numbers[i]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.