如何使用2d数组读取csv文件

时间:2015-07-02 12:34:40

标签: c++ csv

我已经完成了使用单维数组,想要使用二维数组转换它。由于我是初学者,我无法做到。请帮我转换这个程序使用二维数组并谢谢你预先

#include<stdio.h>

#include<string.h>

FILE *file;
char str[20];
char buffer[128];
char *token;
char *a[20],b[20];

int main ()
{
    int i=0;
    printf("\n Enter the file name:");
    scanf("%s",&str);

    file=fopen(str,"r");
        if(file != NULL)
        {
            while(fgets(buffer,128,file) != NULL)
            {
                token = strtok(buffer,",");
                while(token != NULL)
                {
                    a[i]=strdup(token);
                    printf("%s\t",a[i]);
                    token = strtok(NULL,",");
                    i++;
                }

            }
        }

        else
        {
            printf("\n the file name you have entered doesnot exist");
        }
    fclose(file);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

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

int e,f;
FILE *file;

char buffer[128];
char *token;
int n,m;
char *a[10][10];
int i=0,j;

void find_keyword()
{
    while(fgets(buffer,128,file) != NULL)
    {
        token = strtok(buffer,",");
        j=0;
        while(token != NULL)
        {
            a[i][j]=strdup(token);
            printf("a[%d][%d]=%s\t",i,j,a[i][j]);
            token = strtok(NULL,",");
            j++;
        }
        i++;
    }
}

void main ()
{
    printf("Enter the values of m and n?\n");
    scanf("%d",&m);
    scanf("%d",&n);

 file=fopen("D:/test.csv","r");
printf("File Open\n");
if(file != NULL)
{
    find_keyword();
}   
else
{
    printf("\n the file name you have entered doesnot exist");
}
fclose(file);
printf("\nFile Closed\n");
}