【问题标题】:How to load stack from CSV? C++如何从 CSV 加载堆栈? C++
【发布时间】:2020-06-04 05:03:37
【问题描述】:

我正在尝试读取一个 .CSV 文件,然后将其放入堆栈中,该文件包含以下数据:id、名称、日期、编号(该文件没有标题仅供参考)

-示例:

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

10,利亚姆,2018 年 8 月 18 日,25 日

18,伊桑,2020 年 2 月 13 日,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;
}

【问题讨论】:

  • 您所说的“堆叠它们”是什么意思尚不清楚。您想要id 排序的数据记录吗?无关的,注意while( !in.eof() )It's a bug that will get you sooner or later.
  • 我想要的是从 .CSV 文件的每一行中取出第一个数据并将其放入堆栈中。

标签: c++ csv stack


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-18
  • 2017-02-17
  • 1970-01-01
  • 2012-07-29
  • 2012-04-18
相关资源
最近更新 更多