Reputation: 2060
I have a rather simple C++-problem, but coming from a C-background I am not really aware of all the I/O capabilities of C++. So here is the problem:
I have a simple .txt file with a specific format, the textfile looks like this:
123 points are stored in this file
pointer number | x-coordinate | y-coordinate
0 1.123 3.456
1 2.345 4.566
.....
I want to read out the coordinates. How can I do this? The first step is fine with:
int lines;
ifstream file("input.txt");
file >> lines;
This stores the first number in the file (i.e. the 123 in the example) in lines. Now I'd like to iterate over the file and only read the x and y coordinates. How can I do this efficently?
Upvotes: 3
Views: 1716
Reputation: 62975
#include <cstddef>
#include <limits>
#include <string>
#include <vector>
#include <fstream>
struct coord { double x, y; };
std::vector<coord> read_coords(std::string const& filename)
{
std::ifstream file(filename.c_str());
std::size_t line_count;
file >> line_count;
// skip first two lines
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::vector<coord> ret;
ret.reserve(line_count);
std::size_t pointer_num;
coord c;
while (file >> pointer_num >> c.x >> c.y)
ret.push_back(c);
return ret;
}
Add error handling where appropriate.
Upvotes: 3
Reputation: 1118
Use the while loop
char buffer[256];
while (! file.eof() )
{
myfile.getline (buffer,100);
cout << buffer << endl;
}
and then you need to parse out your buffer.
EDIT: The correct for using a while loop with eof is
while ((ch = file.get()) != EOF) {
}
Upvotes: -1
Reputation: 490108
I'd probably do it just about like I would in C, just using iostreams:
std::ifstream file("input.txt");
std::string ignore;
int ignore2;
int lines;
double x, y;
file >> lines;
std::getline(ignore, file); // ignore the rest of the first line
std::getline(ignore, file); // ignore the second line
for (int i=0; i<lines; i++) {
file >> ignore2 >> x >> y; // read in data, ignoring the point number
std::cout << "(" << x << "," << y << ")\n"; // show the coordinates.
}
Upvotes: 4