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

How to load stack from CSV? C++

本文关键字:堆栈 C++ 加载 CSV      更新时间:2023-10-16

我正在尝试阅读.CSV文件,然后将其放入堆栈中,该文件包含如下数据:id,名称,日期,num(该文件没有标题仅供参考(

-例:

12, 梅森, 08/12/2019, 58

10, 利亚姆, 08/18/2018, 25

18, 伊森, 02/13/2020, 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 << "ntEmpty stackn";
} else {
cout << "tStack is: " ;
while( cursor != NULL ) {
cout << cursor->id << "->";
cursor = cursor->next;
}
cout << "NULLnn";
}
cout << endl;
}

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

  1. 阅读每一行。
  2. 根据逗号字符将每行拆分为一个数组。
  3. 将数组的第一项放到堆栈上。