如何使用c++将CSV文件的内容显示到数组中

How display content of CSV file into an array using c++

本文关键字:显示 数组 c++ 何使用 CSV 文件      更新时间:2023-10-16

我想以行和列的形式显示csv数据,例如
名称uid类
nnn 1 A
bbb 2 B
ccc 3 A

这就是我迄今为止所尝试的:

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
    clrscr();
    ifstream ifile;
    char s[100], fname[20];
    cout<<"Enter file name to read and display its content" ;
    cin>>fname;
    ifile.open(fname);
    if(!ifile)
    {
        cout<<"Error in opening file..!!";
        getch();
        exit(0);
    }
    while(ifile.eof()==0)
    {
        ifile>>s;
        cout<<s<<" ";
    }
    cout<<"n";
    ifile.close();
    getch();
}

这是我显示csv数据的代码,但它实际上在一行中显示了所有数据。

您可以使用getline成员函数来获取完整的行。然后更改这一行:

cout<<s<<" ";

cout<<s<<"n";

此外,我认为你的while循环条件是不正确的。

使用std::getline读取一行(包括逗号)。从这行生成std::stringstream

然后使用std::getline根据逗号分隔行。您将不得不使用嵌套循环。

代码草图:

std::string line, word;
while (std::getline(ifile, line))
{
    std::stringstream stream(line);
    while (std::getline(stream, word, ','))
    {
        ... (whatever you want to do with each word)
    }
    std::cout << 'n'; // whatever you want to do at end of line
}

.csv文件的一行(行)中的单元格用";"检查

例如,当您从.csv文件中读取一行时,该行的每一列都用";"进行检查符号,您可以将其用于一行中的单独列!