Reputation: 14670
Hi I have a text file which contains some numerical data. Of that text file ONLY the lines 14 to 100 have to be read into my C++ program. Each of these lines contain three numbers corresponding to x,y,z coordinates of a point. Thus, coordinates are given for 87 points in all.
I want to put these numbers into the arrays xp[87] yp[87] and zp[87].
How do I perform this?
Uptil now I have been used to the following
ifstream readin(argv[1])//Name of the text file
for (int i=0; i<=86; ++i)
{
readin>>xp[i]>>yp[i]>>zp[i];
}
But this technique works only for those files which contain 87 lines and the data to be read starts from the first line itself.
In the present case I want to ignore ALL lines before line 14 and ALL lines after line 100
Upvotes: 2
Views: 4984
Reputation: 28480
After several years, Range-v3 allows one to write this:
#include <fstream>
#include <iostream>
#include <range/v3/view/drop.hpp>
#include <range/v3/view/getlines.hpp>
#include <range/v3/view/take.hpp>
using namespace ranges;
using namespace ranges::views;
int main() {
std::ifstream ifs{"inputFile"};
auto lines = getlines(ifs) | take(100) | drop(15/* which is 14 - 1 */);
for (auto i : lines) {
std::cout << i << std::endl;
}
}
Requires C++17.
Upvotes: 0
Reputation: 81379
In the present case I want to ignore ALL lines before line 14
Since you have to actually read the file to know where a line ends and a new one begins, you will have to then read 13 lines. Use getline()
and a dummy string to hold the results from it.
and ALL lines after line 100
Just close the stream and be done with it.
Upvotes: 0
Reputation: 477398
Read line by line, for most flexibility in your format:
#include <fstream>
#include <sstream>
#include <string>
std::ifstream infile("thefile.txt");
std::string line;
unsigned int count = 0;
while (std::getline(infile, line))
{
++count;
if (count > 100) { break; } // done
if (count < 14) { continue; } // too early
std::istringstream iss(line);
if (!(iss >> x[count - 14] >> y[count - 14] >> z[count - 14]))
{
// error
}
}
// all done
Upvotes: 5