Question

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;
in.open("someData.txt");
while(!in.eof())//the text from the file is stored in different variables
   {
   in>>inputData[0];
   in>>inputData[1];
   }

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++ ?

Was it helpful?

Solution

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");
while(in>>inputData[0])
{
   in>>inputData[1];
}

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

std::string line;
while(getline(std::cin,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];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top