-1

I am trying to read text file line by line and then read each column as vector but when i am tryin to cout first column it shows zeros i.e. not reading the file correctly.

int main(void)
{


    ifstream myfile ("data1.txt");
    string line;


    if (myfile.is_open())
   {

        int ln=1;

     while ( getline (myfile,line) )
     {      
      if(ln==1){ln++; continue;}
        istringstream iss(line);
        string word;
        vector<double> column;
        int w=1;
        while(iss >> word) 
        {   

            //double dw=atof(Form("%s",word));      
            column.push_back(atof(Form("%s",word)));
            cout<<column[0];

        w++;


        }

    ln++;
    cout<<"\n";
    }
   myfile.close();
  }
  //else
  else cout<<"Unable to open file"; 
  cout<<"\n";
  return ;
  }enter code here

2 Answers2

0

push_back appends an element as last element of the vector while columns[0] always refers to the first element of the vector.

Is the first element 0

Is there another problem?

(Please explain what is Form, give an example of input file and output in the command line)

styko
  • 641
  • 3
  • 14
  • yes first column's first element is zero. yes there is another problem i want to use these vectors in plotting graphs using root framework. Form is used to read word as string and also because atof takes 1 parameter to convert string into double. i only want my text to be stored as double in the vector. – user4823966 Jul 27 '15 at 09:20
  • But why not use `word.c_str()` which is the standard way to convert a `string` to a `char[]` suitable for `atof`? – styko Jul 27 '15 at 09:23
  • I would say string stream is a more standard way.. c_str does not return char */char[] it returns const char */const char []. – TLOlczyk Jul 27 '15 at 09:34
  • Where is the problem if you pass it to `atof`? – styko Jul 27 '15 at 09:37
  • when using atof it is giving me zero as value – user4823966 Jul 27 '15 at 09:39
  • @styko It tempts you to use ftoa and itoa. – TLOlczyk Jul 27 '15 at 09:48
0

First of all learn how to indent and consistently use some scheme for inserting blank lines that makes sense. When you do that you can read your own code and figure out if it is doing what you think it is.

Second. Save Form("%s",word) in a string ( for now call it form_string) add this line cout<<"form returns "<<form_string<<endl; 99.99% probably it will print zeros.

Finally change: cout<<column[0]; to cout<<column[0]<<" "; or cout<<*(column.rbegin())<<" ";. The latter prints out all the values that you read, the former prints out the first value you read over and over.

TLOlczyk
  • 443
  • 3
  • 11