Search code examples
c++structurestack-overflow

Stack overflow error while trying to copy .csv data to structure in c++


I am trying to read a .csv file into a c++ algorithm and I am trying to store each column in different string arrays built into a structure.. I was doing the work alright until the error of stack overflow came on.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;
struct burgerking //structure containing different strings for each column in .csv file
{
    string longitude[7000];
    string latitude[7000];
    string location[7000];
    string state[7000];
    string address[7000];
};

void main () {
    burgerking burger;
    string line;
    ifstream myfile;
    myfile.open("burgerking.csv"); //opening the csv file
    if(myfile.good())
        cout<<"File is Good to be opened"<<endl;
    int l=0;
    int n=1;
    int e=2;
    int ss=3;
    int j=0;
    int b=0;
    int kk=0;
    int ll=0;
    for(int i=0;i<40;i++)
    {
        getline(myfile,line,',');
        if(i==0)
        {
            burger.longitude[j]=line;
            j++;
            l=l+7;
        }
        if(i==l)
        {
            burger.longitude[j]=line.substr(16,line.length());
            j++;
            l=l+7;
        }
        if(i==n)
        {
            burger.latitude[b]=line;
            n=n+7;
            b++;
        }
        if(e==i)
        {
            burger.location[kk]=line;
            kk=kk+1;
            e=e+7;
        }
        if(ss==i)
        {
            burger.state[ll]=line;
            ss=ss+7;
            ll++;
        }
    }

    //myfile.close();
    //myfile.open("burgerking.csv");
    //for(int c=0;c<20;c++)
    //{
    //  getline(myfile,line,',');
    //  if(c==3)
    //  {
    //      burger.address[0]=line;
    //  }
    //}

    for(int k=0;k<1;k++)// loop just to check the program output
    {
        cout<<burger.state[k]<<endl; //just to check the output 

    }



    myfile.close();
    system("PAUSE");
}

Solution

  • You are creating a very big structure on the stack. Your "burger" variable is taking at least 140 Kb of the stack space which is too much. I suggest you to allocate it from the heap, i.e.

    burgerking* burger;
    burger = new burgerking();