我试图读取一个.CSV文件,然后把它放到一个堆栈中,该文件包含这样的数据:id,name,date,num(该文件没有头,仅供参考)。
-例子。
12,梅森,08122019,58。
10、Liam,08182018,25岁
18,Ethan,02132020,15岁。
#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;
}
将CSV文件视为文本文件,照常读取。