read text file column wise c++

Go To


I have a text file where data is stored as columns. How do I extract each column in to an array?

eg: a b c d

10 11 12 13

 14 15 16 17

I want four arrays as, a = {10,14}, b = {11,15} c = {12,16} d = {13,17}

Below is what I have done so far to add them in to a single array:

CArray <double,double> *data = new CArray <double,double>();

CString strLine;


  CStdioFile file(m_fileName, CFile::modeRead); 

  while(file.ReadString(strLine)) {
      CArray <double,double> arrayValues;

      for (int i=0; i< arrayValues.GetSize()-1;i++){
        //  Temp_data[i] = arrayValues.ElementAt(i);
  e->ReportError(); // shows what's going wrong 

void splitString(CString S, CArray<double,double>& arrayValues){

CString sep = _T(" ");
int start = 0;
CString aux = S.Tokenize(sep, start);
while(start != -1){
      aux = S.Tokenize(sep, start);




2012-04-04 07:21
by gishara
You mean to name the array from a value from text file? - Rohit Vipin Mathews 2012-04-04 07:25


Since you havent tried anything till i will give some suggestions to you.

first take the line into a string and split it and then store all the values in an array. so at the end you will have total lines of arrays.

now use the indexes and store them in different column array based upon the indexes like : all the elements in the arrays with similar index will be stored in array colN.

2012-04-04 07:27
by Vijay


Tip - Hope you wont mind I did not write the code for you :)

  • Read the file using inputstream.
  • Split the line read by tokenising the input data.
  • Use atoi() method to convert the strings to integers and populate your arrays.
2012-04-04 07:33
by NoName
I'd do similar but use stringstream instead of atoi - graham.reeds 2012-04-04 08:01