c - 一次将一行二维数组存储在一起
问题描述
我有一个问题,将我同时从文件 csv 读取的行的所有值一起存储到二维数组中。
这是我的代码:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define BUFSIZE 1024
int main()
{
char *filename = "pb0.csv";
char str[BUFSIZE];
FILE *fpr;
fpr = fopen(filename, "r");
int i,j;
const int row = 449;
const int column = 6;
int family[row][column];
int c,d,e,f,g,h;
if (fgets(str, BUFSIZE, fpr) != NULL) {
while(fscanf(fpr, "%d; %d; %d; %d; %d; %d", &c,&d,&e,&f,&g,&h) != EOF){
for(i=0;i<row;i++){
for(j=0;j<column;j++){
//add code here
}
}
}
}
//printf("%d",n);
fclose(fpr);
return 0;
}
任何帮助将不胜感激。
解决方案
我会说您显示的代码至少有两个问题。首先是您阅读并忽略了第一行。第二个是你不能很好地处理错误。第三是您从文件中读取一个“行”,然后遍历所有二维数组(当您只需要设置单行的值时)。
通过一些更改,您可以解决所有这三个问题(第三个问题似乎是您要问的):
int current_row = 0;
// Read all lines in a loop
while (fgets(str, BUFSIZE, fpr) != NULL)
{
// Parse the line we just read, read directly into the row
if (sscanf(str, "%d; %d; %d; %d; %d; %d",
&family[current_row][0],
&family[current_row][1],
&family[current_row][2],
&family[current_row][3],
&family[current_row][4],
&family[current_row][5]) == 6)
{
// Parsing successful, advance to the next row
++current_row;
}
}
// All data read from the file
// The number of lines that was actually read and successfully parsed is in
// the variable current_row
// Example iterating over all records that were read from the file
for (int i = 0; i < current_row; ++i)
{
printf("family[%d][0] = %d\n", i, family[i][0]);
}
推荐阅读
- c# - 多值 XML 项到 C#
- r - 多个 y 轴使用 plotly 和不同长度的数据
- android - 复合查询未给出正确结果 [Firestore]
- smtp - 如何使用任何 Gmail、outlook、yahoo 帐户的 Javascript 查找 imap 设置
- c# - 如何使用功能应用程序更新共享点在线网站集
- azure - 如何从管道 Azure Devops 访问私有存储库?
- angular - 错误加载包'':每个.bzl文件必须有一个对应的包,但'@npm//:install_bazel_dependencies.bzl'没有
- android - java.lang.IllegalStateException: getResources() 或 getAssets() 已被调用
- apache - 将 https://www.website.com 重定向到 https://website.com 不起作用
- ajax - Ajax GET 请求上的 Rust Hyper CORS 策略错误