confusedMind confusedMind - 1 year ago 87
C++ Question

How to read txt file C++ and split them into columns

This is the first time i am writing code in c++ (Visual studio 2010) . I have the logic i want to implement but i cannot put it to code. Have looked on many samples but nothing found.

Basically i have a tab delimited txt file and i want to read it and put the data into string,string array anything.

The issue is using the built in :

ifstream in;"someData.txt");
while(!in.eof())//the text from the file is stored in different variables

Will put the data into string array but splitting the row by Space even if the space occurs in the data row it will break it into two columns which is the problem.

How can i properly read data line by line and into columns using c++ ?

Answer Source

If your column data may contain spaces, better use " around string or add '\t' as delimiter.

You can reorder your code to use as shown below to ensure you don't read an empty line at last.

ifstream in("someData.txt");

Or even better if entry of second column in any line is missing.

std::string line;
  // Splitting into 2 in case there is no space
  // If you colum may contain space, replace below lines with better logic.
  std::istringstream iss(line);
  inputData[0] = inputData[1] = default_value;
  iss >> inputData[0] >> inputData[1];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download