When reading a file (ifstream) is there a way to pipe it to create a newline?

When reading a file (ifstream), is there a way to pipe it to create a newline?

For example, I would like this to happen:

MyFile → array [1] → array [2] → epsI;

Obviously "endl" is simply not allowed. Is there any other way to do this?

Edit --- thanks for the quick answers guys!

From a text file, I am trying to store two lines from that file into arrays, and then do the same with the next line (or until I want to, using a for loop)

Using strings is important to me as it will make my future program more flexible.

+1


source to share


5 answers


Several parameters:

You can use ignore.

myfile >> array[1] >> array[2];
myfile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

      



Or you can read each line as a stream of lines

std::string line;
std::getline(myfile,line);
std::stringstream  stream(line);

stream >> array[1] >> array[2];

      

Note: array indexing starts at 0.

+4


source


Use std::getline

to read lines in memory stream, then get two lines from that.



while (cin)
{
  string line;
  getline(cin, line);

  stringstream stream;
  stream << line;

  stream >> array[1]>>array[2];
}

      

+3


source


Read your two items then call myfile.ignore(8192, '\n')

+2


source


I have no idea what this question means. Here's an easy way to read all lines of a file into a vector of lines. It may be easier for you to do what you want to do if you do it first.

std::vector<std::string> lines;

std::string line;
while (std::getline(myFile, line))
    lines.push_back(line);

      

Now you can say lines[4]

to get the fifth row, or lines.size()

to find out how many rows there were.

+1


source


This should work:

stringstream stream;
string sLine;
int iLine;

while (cin)
{
  getline(cin, sLine);

  stream << sLine;
  stream >> data[iLine][0] >> data[iLine][1];
}

      

Custom version of earlier answer.

0


source







All Articles