首页 > 解决方案 > How to write correctly a file in C?

问题描述

I am learning basic programming in C and I have problems with a file writing exercise. The problem is to write a square matrix in a file but in the following way: The first two numbers in each row should be separated by "," and then write the remaining numbers separately.

It is a fairly simple exercise but I am just learning, I leave my code that has some flaws. I hope you can help me.

#include <stdio.h>
int main(){
FILE *data;
int matrix[4][4] = {
    {1,2,3,4},
    {2,3,5,6},
    {9,8,4,5},
    {5,3,1,2}
};
data = fopen("output.txt","w");
for (int i = 0; i < 4; ++i)
{
    for (int j = 0; j < 4; ++j)
    {   
        if(matrix[i][0]>=0&&matrix[i][j+1]<4)
        {
        fprintf(data, "%d,%d ",matrix[i][j],matrix[i][j+1]);
        }
        else
            fprintf(data, "%d ",matrix[i][j]);
    }
    fprintf(data, "\n");
    }
   fclose(data);
 return = 0;
 }

I Know that my big mistake is the condition of the if sentence but I don't know how to write that correctly for this case.

I want to obtain this output:

1,2 3 4
2,3 5 6
9,8 4 5
5,3 1 2

How can I fix the if sentence or do something different to obtain that output?

标签: c

解决方案


You were close but your logic was a little off, try printing them one at a time and then checking for the index of the inner for loop to be the 0 index and then append the comma on the end.

Also on you return statement you are providing the value to return hence: return 0; you cannot assign return a value

Hope that helps, I did mine using printf and then changed it back to fprintf so there could be an error with that you may have to fix

#include <stdio.h>

int main(){

    FILE *data;
    int matrix[4][4] = {
        {1,2,3,4},
        {2,3,5,6},
        {9,8,4,5},
        {5,3,1,2}
    };
    data = fopen("output.txt","w");

    for (int i = 0; i < 4; ++i)
    {
        fprintf(data, "%d,", matrix[i][0]);
        for (int j = 1; j < 4; ++j)
        {   
            fprintf(data, "%d ", matrix[i][j]);
        }
        fprintf(data, "\n");
    }
    return 0;
 }

推荐阅读