将具有不同数据类型的csv数据保存到C中的数组中

问题描述 投票:0回答:1

嗨,大家好我在尝试读取数据并将数据从csv文件保存到数组时遇到麻烦,我已经成功读取并将其保存为char类型数据,但我需要将数字保存为int数据类型,所以我可以使用数学运算,有人可以帮助我吗?

这是我的csv文件内容:

Nama,Gaji,Zakat,Gaji Bersih
Ali,1234567,,
Sofyan,2345678,,
Kholimi,3456789,,

我还需要将“Nama,Gaji,Zakat和Gaji Bersih”保存到阵列中。

这是我的代码只能将csv文件中的内容保存到char数组:

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

int main()
{
   char buffer[1024] ;
   char *record,*line;
   char nama[10][100];
   int i=0,j=0,c=0,gaji[10][100],zakat[10][100],bersih[10][100];
   int mat[100][100];
   FILE *fstream = fopen("Tugas03.csv","r");
   if(fstream == NULL)
   {
      printf("\n file opening failed ");
      return -1;
   }
   while((line=fgets(buffer,1024,fstream))!=NULL)
   {
     record = strtok(line,",");
     while(record != NULL){
       strcpy(nama[c], record);
       c++;
       printf("\t%s",record);
       mat[i][j++] = atoi(record) ;
       record = strtok(NULL,",");
     }
     ++i ;
   }
   return 0 ;
 }

有人帮我请...

这是我的新代码:

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

int main()
{
   char buffer[1024] ;
   char *record,*line;
   char nama[10][100],temp[100];
   int i=0,j=0,c=0,gaji[10][100],zakat[10][100],bersih[10][100];
   int mat[100][100];
   FILE *fstream = fopen("Tugas03.csv","r");
   if(fstream == NULL)
   {
      printf("\n file opening failed ");
      return -1;
   }
   while((line=fgets(buffer,1024,fstream))!=NULL)
   {
     record = strtok(line,",");
     while(record != NULL){
       if(c==0||1||2||3||4||8||12){
        strcpy(nama[c], record);
       }else if(c==5||9||13){
        strcpy(temp, record);
        gaji[c][100] = atoi(temp);
       }
       c++;
       //printf("\t%s",record);
       mat[i][j++] = atoi(record) ;
       record = strtok(NULL,",");
     }
     ++i ;
   }
   printf("\t%s\n", gaji[0]);
   printf("\t%s\n", nama[0]);
   printf("\t%s\n", temp);
   return 0 ;
 }
c arrays csv
1个回答
0
投票

目前还不清楚您希望如何存储数据,因此很难为您提供帮助。

但这是一个主要问题:

你需要在每个循环中将j设置为零。

喜欢:

   while((line=fgets(buffer,1024,fstream))!=NULL)
   {
     j = 0;  // Add this line

     record = strtok(line,",");
     while(record != NULL){
       strcpy(nama[c], record);
       c++;
       printf("\t%s",record);
       printf(" (%d)", atoi(record));  // For test add this line
       mat[i][j++] = atoi(record) ;
       record = strtok(NULL,",");
     }
     ++i ;
   }

如果在输入文件中运行上面的代码:

N,G,Z,GB
A,1,2,3
B,4,5,6
C,7,8,9

你会得到:

    N (0)   G (0)   Z (0)   GB (0)
    A (0)   1 (1)   2 (2)   3 (3)
    B (0)   4 (4)   5 (5)   6 (6)
    C (0)   7 (7)   8 (8)   9 (9)

如您所见,数字已根据需要转换为int

这段代码的问题是它试图将每个标记(即名称和数字)转换为int。你可以做到,但它可能不是你想要的。如果没有,您需要重新设计代码。

第1步是明确计划如何存储数据。

也许你想要的东西:

struct data {
    char nama[100];
    int Gaji;
    int Zakat;
    int Gaji_Bersih;
};

存储行(标题除外)

请注意,strtok对于这种解析是一个糟糕的选择,因为它会跳过空令牌。

© www.soinside.com 2019 - 2024. All rights reserved.