0

I am trying to read a .CSV file and then put it into a stack the file contains data like this: id, name, date, num (The file has no header is for reference only)

-Example:

12, Mason, 08/12/2019, 58

10, Liam, 08/18/2018, 25

18, Ethan, 02/13/2020, 15

What I want is to take the first data from each row of the .CSV file and put it on the stack.

#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;
}

Erick
  • 1
  • 3
  • 1
    What you mean by "stack them" is unclear. You want the data records ordered by `id`? Unrelated, watch out for `while( !in.eof() )`. [It's a bug that will get you sooner or later.](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – user4581301 Jun 03 '20 at 20:00
  • What I want is to take the first data from each row of the .CSV file and put it on the stack. – Erick Jun 03 '20 at 20:03

1 Answers1

0

consider the CSV file as a text file and read it as usual.

  1. Read each line.
  2. Split each line on the basis of comma character into an array.
  3. Put the first item of the array on to the stack.
user366312
  • 16,949
  • 65
  • 235
  • 452
  • I just want to know what I have to read the CSV with, if you can I would appreciate it. – Erick Jun 03 '20 at 20:48
  • @Erick, I don't have a C++ compiler installed at this moment. Anyway, consider the CSV file as a text file and read it as usual. – user366312 Jun 03 '20 at 20:52
  • 1
    @Erick, [Read file line by line using ifstream in C++](https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c) – user366312 Jun 03 '20 at 20:53
  • @Erick, [Parsing a comma-delimited std::string](https://stackoverflow.com/a/1894955/159072) – user366312 Jun 03 '20 at 20:54
  • @Erick, [Making a stack using linked list in C](https://www.codesdope.com/blog/article/making-a-stack-using-linked-list-in-c/) – user366312 Jun 03 '20 at 20:56