Thishan Dharmakeerthi
Thishan Dharmakeerthi

Reputation: 83

Why is my global variable vector not storing my data?

I read a text file which includes "," separated words.

I read this file line by line.

After taking a line, I split it in to words by using split function. Here I use ',' for separate words from the line.

I defined a global vector so I thought I can store all the words in that vector.

Everything works fine until the vector come out from the split function.

Code works fine. But it dose not store the words in the vector.

At the bottom of the split function you can see the line I've written. cout<<evec.size()<<endl; that line is to check the size of the vector line by line.

If the first line have 13 comma separated words it shows 13 (Which means it stored it)

But as soon as you get out from the split function, that data is no longer available. what can i do to store all words in this vector?

#include<iostream>
#include<string>
#include<stdio.h>
#include <fstream>
#include <vector>

using namespace std;

std::vector<string> evec;


void split( string st,vector<string> evec){
   string z = " ";
   for ( char s : st){
      if ( s==','){
        evec.push_back(z);
         z = " ";
      }
      else{
         z = z + s;
      }
   }
   cout<<evec.size()<<endl;

}

int main( ){
string st;
ifstream Myfile("file.txt");
   while(getline(Myfile, st))
{
    split(st,evec);
    
}
    cout<< evec.size() <<endl;
    for (auto& it : evec) {
        cout << it << endl;
    }
   return 0;
}

Upvotes: 1

Views: 202

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

void split( string st,vector<string> evec){

The 2nd parameter to this split() function is called evec. It has absolutely nothing to do, whatsoever, with the global variable that just happens to have the same name. Just because it has the same name as the global variable doesn't mean that it's the same object, it is not.

Additionally, it gets passed to this function by value. This function makes changes to its evec parameter. "By value" means that, effectively, this parameter is a copy of the original parameter that was passed to this function, and any changes to this parameter have no effect on the object that was passed in, it's just an independent copy.

A "global variable", by definition, does not need to be passed in to a function. It is globally accessible. Simply remove this parameter from this function.

On the other hand, a different approach is needed if you do not really want to use a global variable. But you stated that the global variable was intentional.

Upvotes: 2

Related Questions