C++: Read text file into 2d array - c++

I'm trying to read the following maze.txt file:
35
35
0
10
++++++++++S++++++++++++++++++++++++
++++++++++OOOOOOOOOOOOOOOOOOOOOOOOO
++++++++++O++++++++++++++++++O+++++
OOOOOOOOOOOOOOOOOOOOOOOOOO+++O++OOE
O+++++++++O++++++++++++++O+++O++O++
OOOOOO++++O++++++++++++++O+++O++O++
O++++O++++OOOOOOOOOOO++++O+OOO++O++
O++++O++++O+++++++++OOOO+O+++O++O++
OOO++OOOO+OOOOOO+++++++++++OOO++OOO
O+O+++++O++++++OOOOOOOOOO++O++++++O
O+OOOO++O++++++O++++++++O+++OOO+++O
O++++O++OOOOOOOO++++++++O+++O+O+++O
OOO++O++++++++++++++++++OOOOO+O+++O
++O++OOOOOOOOOOOOOOOO+++++++++OO++O
OOO+++++++++++++++++OOOOOO++++++++O
O++++++++++++++++++++++++O++OOOOOOO
+++++++++++++++++++++++++O++O++++++
OOOOOOOOOOOOOOOOOOOOOOOOOO++OOOOO++
O++++++++++++++++++++++++O++++++O++
OOOOOOO+++++++++++++++OOOOOOO+++O++
++++++++++++++++++++++O+++++OO++O++
OOOOOOOOOOOOOOOOOOOOOOO++++++O++O++
O++++++++++++++++++++++++++++O+OOOO
OOOO++++++++++++++++++++OOOOOO+O+++
+++OOOOOOOOO+++++++++++++++++++O+++
+++++O+++++OOOOOOOOOO++++++++OOO+++
+O+++OOOOO++++++O++++++++++++O+++++
+OOOOO+++O++++++OOOOOO+++++++O+++++
+++++++++++++++++++++OOOOOOOOO+++++
OOOOOOOOOOOOOOOOOOOOOO+++++++++++++
+++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++
The code works fine with the maze inside the code but I moved it out to a text file, which seems to be read but it is not working. It's giving me the error:
No matching function for call to 'mazeTravel'.
I'm not sure where to go from here. Any help would be appreciated!
#include <iostream>
#include <fstream>
using namespace std;
void printMaze(const char maze[][12], int xCoordinate, int yCoordinate);
int mazeTravel(char maze[][12], int xCoordinate, int yCoordinate, int direction);
int main()
{
char maze[35][35];
ifstream file;
file.open("maze.txt");
if (!file) {
cout << "Error reading file\n";
return -1;
}
else {
for (int row = 0; row < 35; row++) {
for (int column = 0; column < 35; column++) {
file >> maze[row][column];
int success = 0;
success = mazeTravel(maze, 2, 0, 1);
if (success == 1)
cout << "The maze has been solved.\n";
else
cout << "Sorry, the maze cannot be solved\n";
}
}
}
return 0;
}

You could use a std::vector of std::strings to represent your maze:
std::vector<std::string> maze;
To access its cells use
maze[row][column]; // with row being y and column x
To get the number of rows use
maze.size()
and
maze[0].size()
for the number of columns.
You could read such a maze like that (without error checking to not clutter the code):
std::vector<std::string> readMaze(std::istream &is)
{
std::size_t columns;
std::size_t rows;
is >> columns >> rows;
int foo; // sorry, don't know what the 3rd and 4th
is >> foo >> foo; // number is. a starting position, perhaps?
// ignore the rest of the current line:
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::string line;
std::vector<std::string> maze;
while (std::getline(is, line))
maze.push_back(line);
return maze;
}
An implementation (with error checking) could look like that:
#include <cstdlib> // EXIT_FAILURE
#include <limits> // std::numeric_limits<>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
// to not have to type std::vector<std::string> all over the place
using maze_type = std::vector<std::string>;
void printMazeCell(maze_type const &maze, std::size_t x, std::size_t y)
{
std::cout.put(maze[y][x]);
}
void printMaze(maze_type const &maze)
{
for (auto const &row : maze)
std::cout << row << '\n';
}
int mazeTravel(maze_type const &maze, std::size_t x, std::size_t y, int dir)
{
// access cells of the maze with maze[y][x]
// maze.size() for the number of columns and
// maze[0].size() for the number of rows
return 42;
}
maze_type readMaze(std::istream &is)
{
std::size_t columns;
if (!(is >> columns)) {
std::cerr << "Couldn't read the number of columns :(\n\n";
return maze_type{}; // return an empty maze on error
}
std::size_t rows;
if (!(is >> rows)) {
std::cerr << "Couldn't read the number of rows :(\n\n";
return maze_type{};
}
int foo;
is >> foo >> foo; // sorry, don't know what the 3rd and 4th number is
// ignore the rest of the current line:
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Trying to read a maze with " << columns << " columns ...\n";
std::string line;
maze_type maze;
while (std::getline(is, line)) {
if (line.length() != columns) {
std::cerr << "Found a row that contains only "
<< line.length() << " columns :(\n\n";
return maze_type{};
}
maze.push_back(line);
}
if (maze.size() != rows) {
std::cerr << "The maze only consists of "
<< maze.size() << " rows :(\n\n";
return maze_type{};
}
return maze;
}
int main()
{
char const *filename = "maze.txt";
std::ifstream is{ filename };
if (!is.is_open()) {
std::cerr << "Couldn't open \"" << filename << "\" for reading :(\n\n";
return EXIT_FAILURE;
}
maze_type maze = readMaze(is);
if (!maze.size()) { // readMaze returned an empty maze :(
std::cerr << "Bye.\n";
return EXIT_FAILURE;
}
printMaze(maze);
}

The problem that you don't have the implementation of
int mazeTravel(char maze[][12], int xCoordinate, int yCoordinate, int direction);
You should create the implementation like this:
int mazeTravel(char maze[][12], int xCoordinate, int yCoordinate, int direction)
{
// The implementation
return 0;
}
Another thing: You have to read the first some numbers at the beginning of the file.
35
35
0
10
After that you can read the matrix from the file

Related

How to get int from a line of a text and add them together in c++?

Hi I have got an text file and inside writing:
15 7 152 3078
178 352 1 57
What I want to do is get the int's from first line, sum up the numbers and make it an integer. And than do it for the second line with another int. How can I do that with c++? Thanks for your help.
You can use stringstream to convert a string into integer. And to sum a vector of integer, use accumulate algorithm. You can pass a filename as first argument to the program, by default the program assume the filename as input.txt.
Here is a complete program to demonstrate this.
#include <iostream>
#include <fstream>
#include <sstream>
#include <numeric> // for accumulate
#include <vector>
int main(int argc, char *argv[]) {
std::string filename{"input.txt"};
if(argc > 1) {
filename = argv[1];
}
// open the input file
std::ifstream inputFile(filename);
if(!inputFile.is_open()) {
std::cerr << "Unable to open " << filename << std::endl;
return 1;
}
std::string line;
// read the file line by line
while(getline(inputFile, line)) {
if(line.empty()) continue;
std::stringstream ss(line);
std::vector<int> v;
int x;
// extract the content as integer from line
while(ss >> x) {
v.push_back(x);
}
// add them all
auto total = std::accumulate(v.begin(), v.end(), 0);
std::cout << total << std::endl;
}
}
As in Aamir's answer, but with separate listing of sums and numbers per line. Maybe that helps too.
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int main(int argc, char *argv[]) {
std::string filename{"input.txt"};
if(argc > 1) {
filename = argv[1];
}
// open the input file
std::ifstream inputFile(filename);
if(!inputFile.is_open()) {
std::cerr << "Unable to open " << filename << std::endl;
return 1;
}
std::vector<int> v_numberSum;
std::vector<int> v_numbersPerLine;
std::string line;
// read the file line by line
int i = 0;
while(getline(inputFile, line)) {
if(line.empty()) continue;
v_numberSum.push_back(0);
v_numbersPerLine.push_back(0);
std::stringstream f(line);
std::string s;
int cnt = 0;
while (getline(f, s, ' ')) {
v_numberSum[i] += std::stoi(s);
cnt++;
}
v_numbersPerLine[i] = cnt;
i++;
}
int j = 0;
for (auto intItem: v_numberSum){
std::cout << "sum"<<j<<": " << intItem << " numbers per line: " << v_numbersPerLine[j] << std::endl;
j++;
}
}

strings in if statement

I am trying to write a code which lists all words used in a text file without repeating. I succeeded to list all the words but I always get repeating ,the if statement line 17 always gives the value of 0.I have no idea why , the words are listed properly in the vector. Any suggestion ?
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class reading {
public:
string word;
vector<string> words;
};
int checkifexist(string word) {
reading readingobject;
bool exist = false;
for (int i = 0; i < readingobject.words.size(); i++) {
if (word == readingobject.words[i]) {
exist = true;
break;
}
}
return exist;
}
int main() {
reading readingobject;
ifstream inFile;
inFile.open("Book.txt");
if (inFile.fail()) {
cout << "file didn't open" << endl;
exit(1);
}
readingobject.word.resize(1);
while (!inFile.eof()) {
inFile >> readingobject.word;
if (checkifexist(readingobject.word) == 1)
continue;
cout << readingobject.word << endl;
readingobject.words.push_back(readingobject.word);
}
return 0;
}
Inside of checkifexist(), you are creating a new reading object, whose words vector is empty, so there is nothing for the loop to do, and the function returns 0.
You need to instead pass in the reading object from main() as an input parameter, eg:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class reading {
public:
vector<string> words;
};
bool checkifexist(const reading &readingobject, const string &word)
{
for (size_t i = 0; i < readingobject.words.size(); ++i) {
if (word == readingobject.words[i]) {
return true;
}
}
return false;
/* alternatively:
return (std::find(readingobject.words.begin(), readingobject.words.end(), word) != readingobject.words.end());
*/
}
int main()
{
reading readingobject;
string word;
ifstream inFile;
inFile.open("Book.txt");
if (!inFile) {
cout << "file didn't open" << endl;
return 1;
}
while (inFile >> word) {
if (checkifexist(readingobject, word))
continue;
cout << word << endl;
readingobject.words.push_back(word);
}
return 0;
}
Alternatively, when it comes to tracking unique elements, you can use a std::set instead of a std::vector, eg:
#include <iostream>
#include <fstream>
#include <set>
using namespace std;
class reading {
public:
set<string> words;
};
int main()
{
reading readingobject;
string word;
ifstream inFile;
inFile.open("Book.txt");
if (!inFile) {
cout << "file didn't open" << endl;
return 1;
}
while (inFile >> word) {
if (readingobject.words.insert(word).second)
cout << word << endl;
}
return 0;
}

Sorting a 2D vector of doubles

I have a list of data (in 4 columns) that I would like to sort by a certain column. It was read in from a file to a 2D vector. I the used the std::sort method and wrote my comparator functor. The program compiles and runs, but when I print the first 10 elements it is not sorted, but is certainly different from the order it was added to the 2D vector.
Here is the code:
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
typedef vector<double> Row;
typedef vector<Row> Matrix;
bool sortByFourthColumn(const Row& row1, const Row& row2){
return (double) row1[3] < (double) row2[3];
}
int main(){
std::ifstream infile;
infile.open("Test8_Output.txt");
double x,y,z,E;
char line[200];
int line_count=0;
ofstream outfile;
outfile.open("WO_crp.txt");
if (infile.is_open()){
while (!infile.eof()){
infile.getline(line,170);
if (line[0] != '%'){
outfile<<line<<"\n";
line_count++;
}
else{
}
}
Matrix data(line_count,Row(4));
outfile.close();
std::ifstream myfile;
myfile.open("WO_crp.txt");
int i = 0;
while(myfile >> x >> y >> z >> E){
data[0][i] = x;
data[1][i] = y;
data[2][i] = z;
data[3][i] = E;
i++;
}
myfile.close();
std::sort(data.begin(), data.end(), sortByFourthColumn);
for (int u = 0; u <20; u++){
cout << setprecision(5) << data[0][u] << "\t" << setprecision(5)<< data[1][u] << "\t" << setprecision(5)<< data[2][u] << "\t" << setprecision(5)<< data[3][u] << endl;
}
}
else{
cout << "Error: File is invalid.\n";
}
return(0);
}
EDIT - Sample of what the input file looks like:
EDIT 2 - swapped 4 and line_count in Matrix data(4,Row(line_count));
% Model: CDS_Test8.mph
% Version: COMSOL 5.2.0.220
% Date: Jul 13 2016, 14:33
% Dimension: 3
% Nodes: 86183
% Expressions: 1
% Description: Electric field norm
% Length unit: m
% x y z es.normE (V/m)
0.13774675805195374 0.05012986567931247 0.20735 67.35120820901535
0.13870000000000005 0.04957489750396299 0.20735000000000003 102.8772500513651
0.13870000000000002 0.050800000000000005 0.20735 87.56008679032011
0.13792733849817027 0.050131465727838186 0.20801419247484804 73.55192534768238
0.13674627634411463 0.04992349737428063 0.20735 63.23018910026428
0.13750191177019236 0.0508 0.20735000000000003 67.26176884022838
0.13827743496772454 0.05193409099097887 0.20734999999999998 73.35474409597487
0.13803618792088135 0.05134931748395268 0.20841988134890965 75.3712126982815
0.13905949760011943 0.05141879754884912 0.20734999999999998 83.70739713476813
0.13896970815034013 0.05092428105421264 0.208142746399683 84.73571510992372
0.1390220807917094 0.0501245422629353 0.20817502757007986 85.57119242707628
0.13944867847480893 0.05161480113017738 0.2081969878426443 89.65643851109644
And so on it goes for another 87k lines or so.
I have a list of data (in 4 columns) that I would like to sort by a
certain column.
The problem is that the dimensions of the vector of vectors used to store the data in OP program is not consistent between declaration and use.
A minor problem is the use of while(!infile.eof()){... which should be avoided.
A fixed version is like this:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <array>
#include <algorithm>
#include <iomanip>
using Row = std::array<double,4>; // instead of typedefs
using Matrix = std::vector<Row>;
using std::cout;
bool sortByFourthColumn(const Row& row1, const Row& row2){
return row1[3] < row2[3];
// ^ The cast is unnecessary
}
int main(){
std::string file_name{"Test8_Output.txt"};
std::ifstream infile{file_name, std::ios_base::in};
if ( !infile ) {
cout << "Error: unable to open file " << file_name << '\n';
return EXIT_FAILURE;
}
Matrix data;
data.reserve(90000); // if you are afraid of the reallocations
int count = 0;
std::string line;
// instead of two loops you can use one loop and read the file once
// I'll use std::getline to extract a row in a std::string
while ( std::getline(infile, line) ) {
// skip comments and empty lines
if ( line.empty() || line[0] == '%' )
continue;
++count;
// extract data from the string using a stringstream
std::stringstream ss{line};
Row r;
ss >> r[0] >> r[1] >> r[2] >> r[3];
if ( !ss ) {
cout << "Format error in line " << count << " of file.\n";
break;
}
data.push_back(std::move(r));
}
std::sort(data.begin(), data.end(), sortByFourthColumn);
cout << std::setprecision(5) << std::fixed;
for ( const auto & r : data ) {
for ( auto const &x : r ) {
cout << std::setw(10) << x;
}
cout << '\n';
}
return EXIT_SUCCESS;
}
The output, given the example data is:
0.13675 0.04992 0.20735 63.23019
0.13750 0.05080 0.20735 67.26177
0.13775 0.05013 0.20735 67.35121
0.13828 0.05193 0.20735 73.35474
0.13793 0.05013 0.20801 73.55193
0.13804 0.05135 0.20842 75.37121
0.13906 0.05142 0.20735 83.70740
0.13897 0.05092 0.20814 84.73572
0.13902 0.05012 0.20818 85.57119
0.13870 0.05080 0.20735 87.56009
0.13945 0.05161 0.20820 89.65644
0.13870 0.04957 0.20735 102.87725

Parse a File with C++

I have created code that will execute a file and then will execute code and store that code into a .csv filer shown below
#include <string>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <fstream>
using namespace.std;
int main(){
int foo = 10;
for(int i =1; x<=8 x++){
std::stringstream ss;
ss << "echo " << foo << " | ./triad >> scaling.csv"<<'\n';
std::cout << ss.str().c_str() <<std::endl;
system(ss.str().c_str());
foo=foo*10
}
return 0;
}
The triad program is one that I am given and cannot change. I run basically 10 iterations on it and print the output of that to a scaling.csv, to give me the following output
Length: 10 MFLOP/s: 2541.29
Length: 100 MFLOP/s: 2515.85
Length: 1000 MFLOP/s: 3616.75
and so on...
does anyone know how to parse that file so instead my scaling.csv will look something like this
Key,Value
10,2541.29
100,2515.85
1000,3616.75
Again what gets printed out by triad I cannot change.
Simple:
int main()
{
string s;
int key; float val;
ifstream out("out.txt");
ofstream in("in.txt);
in >> s;
in >> key; // key == 10
in >> s;
in >> val; // val == 2541.29
}
Put this into a function and you have:
void extract(std::istream& in, int& key, float& val)
{
// same as above
}
int main()
{
int key; float val;
while (in)
{
extract(in, key, val);
out << key << ", " << val << std::endl;
}
}
But we're performing the input after we check the stream. This can cause problems. Let's have the extract function return a reference to the stream:
std::ios& extract(std::istream& in, int& key, float& val)
{
// same as above
}
int main()
{
int key; float val;
while (extract(in, key, val))
// ^^^^^^^^^^^^^^^^^^^^^
{
out << key << ", " << val << std::endl;
}
}

Need help loading simple text data with c++

I need help loading a custom file format into my program made in c++...
I know there's a simple way of doing this but I think I'm using the
wrong terms to search for it online...
My custom format for 3d objects is as follows:
NumVerts 6
//verts (float)
-1
-1
0
1
-1
0
-1
1
0
1
-1
0
1
1
0
-1
1
0
//texture (float)
0
0
1
0
0
1
1
0
1
1
0
1
//index (int)
0
1
2
1
3
2
And that is a quad... (yeas; I know... horrible format... but it's what I'm using for an android game).
I want to make a function in c++ for my editor (SDL + OpenGL for windows) that loads these files into data... Unfortunately though I know how to export this format with C++, I can't figure out how to import them... I wish to use the fstream commands...
If someone could quickly write out a simple version I'd be really thankful.
I just it to do the following:
Find text file from input string
read "NumVerts" and grab the integer written after it
loop through the next (NumVerts*3) lines and grab each number as a float
loop though the next (NumVerts*2) lines and grab each number as a float
loop through the next (NumVerts*1) lines and grab each number as an Int
(skip any line that starts with "//")
close file.
Thank you for reading and any help would be really good right now... or a relivent link that is quite simple and reads strings from files and grabs numbers from them to be placed into memory...
I really just want to finish this game and it's getting really stressful trying to locate helpful tutorials.
Update: updated the script... I accidently forgot to seperate 1's and 0's...
Hope this helps. Incidentally, you have the wrong number of vertex components - you need 18 of them.
#include <algorithm>
#include <exception>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/trim.hpp>
#include <boost/lexical_cast.hpp>
using boost::lexical_cast;
int load_3d_object(const std::string& filename,
std::vector<float>& vertComponents,
std::vector<float>& texComponents,
std::vector<int>& indices)
{
std::ifstream fs(filename.c_str());
std::string line;
if(!std::getline(fs, line))
{
throw std::runtime_error("The input file is empty");
}
if(line.substr(0,8) != "NumVerts")
{
throw std::runtime_error("The first line must start with NumVerts");
}
// Extract the number of vertices.
int numVerts = lexical_cast<int>(line.substr(line.find(' ') + 1));
// Read in the vertex components, texture components and indices.
while(std::getline(fs, line))
{
boost::trim(line);
if(line.substr(0,2) == "//") continue;
if((int)vertComponents.size() < numVerts * 3) vertComponents.push_back(lexical_cast<float>(line));
else if((int)texComponents.size() < numVerts * 2) texComponents.push_back(lexical_cast<float>(line));
else indices.push_back(lexical_cast<int>(line));
}
return numVerts;
}
int main()
{
std::vector<float> vertComponents;
std::vector<float> texComponents;
std::vector<int> indices;
try
{
int numVerts = load_3d_object("input.txt", vertComponents, texComponents, indices);
}
catch(std::exception& e)
{
std::cout << e.what() << '\n';
}
return 0;
}
Hopefully this might help (minimal error checking):
int _get_num_verts_value(std::ifstream& a_in)
{
char buf[128];
int result = -1;
a_in.getline(buf, sizeof(buf));
while (a_in.good())
{
if (a_in.gcount() > 9)
{
string s(buf);
if (0 == s.find("NumVerts "))
{
result = atoi(s.substr(8).c_str());
break;
}
}
a_in.getline(buf, sizeof(buf));
}
return result;
}
template <typename T>
void _get_values(std::ifstream& a_in, std::vector<T>& a_values)
{
char buf[128];
a_in.getline(buf, sizeof(buf));
int i = 0;
while (a_in.good())
{
string line(buf);
if (0 != line.find("//"))
{
a_values[i++] = boost::lexical_cast<T>(line);
// All read ?
if (i == a_values.capacity())
{
break;
}
}
a_in.getline(buf, sizeof(buf));
}
}
int main(int /*a_argc*/, char** /*a_argv*/)
{
ifstream in("test.txt");
const int num_verts_value = _get_num_verts_value(in);
std::vector<float> verts(num_verts_value * 3);
_get_values<float>(in, verts);
std::vector<float> textures(num_verts_value * 2);
_get_values<float>(in, textures);
std::vector<int> indexes(num_verts_value);
_get_values<int>(in, indexes);
in.close();
return 0;
}
using a flat file for this purpose could be a bad idea. it's pretty fragile. I prefer to a binary file or a self-described file (e.g xml).
std::ifstream in("in");
char buf[256];
std::string line;
int NumVerts;
in >> buf >> NumVerts;
std::vector<float> verts(NumVerts * 3);
std::getline(in, line);//read the rest of the line
std::getline(in, line);//skip the comment line
std::for_each(verts.begin(), verts.end(), [&in](float& par){
in >> par;
});
std::vector<float> texture(NumVerts * 2);
std::getline(in, line);//read the rest of the line
std::getline(in, line);//skip the comment line
std::for_each(texture.begin(), texture.end(), [&in](float& par){
in >> par;
});
std::vector<int> index(NumVerts);
std::getline(in, line);//read the rest of the line
std::getline(in, line);//skip the comment line
std::for_each(index.begin(), index.end(), [&in](int& par){
in >> par;
});
For the links on how to DIY:
Tutorial: http://www.cplusplus.com/doc/tutorial/files/
Reference: http://new.cplusplus.com/reference/iostream/fstream/
Example code:
#include <string>
#include <iostream> // needed for printing stuff out
#include <fstream> // Needed to read the file
#include <stdexcept>
#include <vector>
using namespace std;
struct Vertice {
double x,y,z; // 3 part stuff to read
double a,b; // 2 part stuff to read
int i; // 1 int thing to read
};
/// Reads a number ignoring comment lines (and any other line that isn't a number)
template <typename T>
T readNumber(istream& data) {
char lastChar;
while (data.good()) {
data >> lastChar; // Don't use peek as that won't skip whitespace
data.putback(lastChar);
if (( (lastChar >= '0') && (lastChar <= '9') ) || (lastChar == '-')) {
// If we're looking at a number read and return it
T result;
data >> result;
return result;
} else {
// If it's not part of a number .. assume it's a comment line and skip the whole line
string commentLine;
getline(data, commentLine);
// TODO: Maybe just skip '//' lines and throw an exception for everything else..
}
}
throw exception("Couldn't read file");
}
double readDouble(istream& data) { return readNumber<double>(data); }
int readInt(istream& data) { return readNumber<int>(data); }
int main(int argc, char** argv) {
if (argc != 2)
cout << "Usage: " << argv[0] << " [DATA_FILE_NAME]" << endl;
else {
fstream data(argv[1], ios_base::in);
data >> skipws; // Skip whitespace
string lastString;
long numVerts = -1;
// Read in words ignoring everything until we hit a 'NumVerts'
while (numVerts < 0) {
data >> lastString;
if (lastString == "NumVerts")
data >> numVerts;
}
// We know how many to get now
typedef vector<Vertice> Verts;
Verts verts(numVerts);
// Read in the triples
for (Verts::iterator i=verts.begin(); i != verts.end(); ++i) {
i->x = readDouble(data);
i->y = readDouble(data);
i->z = readDouble(data);
}
// Read in the pairs (some other data)
for (Verts::iterator i=verts.begin(); i != verts.end(); ++i) {
i->a = readDouble(data);
i->b = readDouble(data);
}
// Read in the single integer value
for (Verts::iterator i=verts.begin(); i != verts.end(); ++i) {
i->i = readInt(data);
}
// Print out all we found
for (Verts::iterator i=verts.begin(); i != verts.end(); ++i) {
cout << "Vertice" << endl
<< " x: " << i->x << endl
<< " y: " << i->y << endl
<< " z: " << i->z << endl
<< " a: " << i->a << endl
<< " b: " << i->b << endl
<< " i: " << i->i << endl
<< endl;
}
}
}
The example code throws an error on the provided files as there isn't enough data to fill out the 'NumVerts'.