如何从CSV中加载栈?C++

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

我试图读取一个.CSV文件,然后把它放到一个堆栈中,该文件包含这样的数据:id,name,date,num(该文件没有头,仅供参考)。

-例子。

12,梅森,08122019,58。

10、Liam,08182018,25岁

18,Ethan,02132020,15岁。

我想从.CSV文件的每一行中提取第一条数据,然后把它放到堆栈中。

#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>

using namespace std;

struct Node{
    int id;
    Node *next;
};

typedef Node *ptrNode;

void addstack( ptrNode *ptrtop, int n );
void printstack( ptrNode cursor );

int main(){

    ifstream in( "file.csv" );
    string s, t;
    Node *stack1 = NULL;
    int dat;

    while( !in.eof() ){
        getline( in, s );
        in >> dat;
        //getline( in, t );  //
            addstack( &stack1, dat );
            printstack( stack1 );
        }

    getch();

    return 0;
}

void addstack( ptrNode *ptrtop, int n ){

    ptrNode ptrnew;
    ptrnew = new Node;

    if ( ptrnew != NULL ) {
        ptrnew->id = n;
        ptrnew->next = *ptrtop;
        *ptrtop = ptrnew;
    }

    cout << "\tAdded: " << n << endl;

}

void printstack( ptrNode cursor )
{
    if( cursor == NULL ) {
        cout << "\n\tEmpty stack\n";
    } else {
        cout << "\tStack is: " ;

        while( cursor != NULL ) {
           cout << cursor->id << "->";
            cursor = cursor->next;
        }
        cout << "NULL\n\n";
    }
    cout << endl;
}

c++ csv stack
1个回答
0
投票

将CSV文件视为文本文件,照常读取。

  1. 读取每一行。
  2. 将每一行根据逗号字符分割成一个数组。
  3. 把数组的第一项放到堆栈中。
© www.soinside.com 2019 - 2024. All rights reserved.