I used below codes to pass a value from vector to my cpp file. While i'm doing that, i got segmentation error in my main cpp? Is there anyway to pass the vector value to my main cpp? thx for the help

void Loadfile()
{
	//cout<<"this is used for loading file"<<endl;//check if the codes passing here
	string line;
    ifstream myfile;
    vector <string> myvector;
    
	myfile.open(DATAFILE);    // Open the datafile
	if (myfile.is_open())     //check If it worked
    {
			while (getline(myfile,line,'\n'))//get whole line from DATAFILE 
           {
											//cout<<i++<<endl;//to test if the codes work correctly
             myvector.push_back(line);		//store them in vector
            }

Well, I can't say much just by looking at your (incomplete)code, but I wonder exactly how you are passing the vector to main() or any other function, as vector<string> myvector; remains a local variable, and looking at your definition of the function LoadFile() , it doesn't return anything.

To answer your second question, why not pass the vector to LoadFile() , so that it gets populated in that way, and remain usable after LoadFile() goes out of scope, like so:

void LoadFile(std::vector<std::string>& myvector)
{
     // Initialize variables
     // Open the file
     // Start reading
     while (getline(myfile,line,'\n'))
          myvector.push_back(line); // Note: you don't have to re-declare myvector
}

int main()
{
    // Some code
    
    std::vector<std::string> myvector;
    LoadFile(myvector);

    return 0;
}

You can also return the vector, instead of passing it by reference, but that's up to you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.