c - 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?
解决方案
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;
}
推荐阅读
- mysql - 掉一个99G的mysql表不影响可以吗?
- android - Android中的双向流导致OOM
- javascript - 从选中的复选框Javascript中获取多个值
- c# - 安装新版本后“找到的程序集的清单定义与程序集引用不匹配”
- css - mydaterangepicker 和 primeng 有问题,它在表头中显示不好,有人可以帮我吗
- javascript - 我正在尝试进行 while 循环,但循环是无限的,我不确定为什么
- docker - 如何设置 php 配置文件 (php.ini) 在 laradock 的 phpmyadmin 容器中使用
- elasticsearch - Elasticsearch 聚合:访问附加字段的策略
- python - 在python中计算给定阈值的置信度
- python - Pandas:使用规则将数据框中两列的字符串值组合成一个新列