while() {
...
if (y == 1)
{
printf("success\n");
FILE* fp2 = fopen("output.txt", "w");
fprintf(fp2, "%d \n", a);
fclose(fp2);
break;
}
}
If the condition is satisfied, I wanted to print the a value to file and success in program.
Many values of a that satisfies the condition was printed in program, but when I checked the output.txt file, there was only the value of the last a.
The reason for using break; is to break out of the loop when meets the condition.
I want to print all the a‘s obtained through the loop.
How can I print all a‘s to a file?
>Solution :
There are two problems:
-
First of all you actively break (stop) the loop once you have printed the first
a. If you want to print all possible values ofacalculated by the loop, you need to let the loop continue. Either by doing nothing or possibly by usingcontinueto start from the top of the loop. -
Once you have fixed the above, you will open, close and reopen the file multiple times in the loop. Because you use the mode
"w"each time you open the file it will be truncated and all its current contents will be lost.Instead open the file once before the loop, keep it open while inside the loop, and close it when the loop actually ends.