Reputation: 517
i have a struct with x,y,z as the type double. I'm trying to split the lines by spaces and then put the values of that array into my structure but it fails to work, can someone tell me what to do?
#include "_externals.h"
#include <vector>
typedef struct
{
double X, Y, Z;
} p;
p vert = { 0.0, 0.0, 0.0 };
int main()
{
char *path = "C:\\data.poi";
ifstream inf(path);
ifstream::pos_type size;
inf.seekg(0, inf.end);
size = inf.tellg();
double x, y, z;
char *data;
data = new char[size];
inf.seekg(inf.beg);
inf.read(data, size);
inf.seekg(inf.beg);
char** p = &data;
char *line = *p;
for (int i = 0; i < strlen(data); ++i)
{
const char *verts = strtok(line, " ");
//this isnt working
vert.X = verts[0];
vert.Y = verts[1];
vert.Z = verts[2];
++*line;
}
}
thanks
Upvotes: 1
Views: 205
Reputation: 141770
You cannot (meaningfully) cast a char*
as a double
, but you can extract from a stream into a double
.
Since you are splitting the input line on spaces, the typical idiom is like this... for each line in the file, create an istringstream
object and use this to populate your structure.
If operator >>()
fails (e.g. if a letter was entered where a digit is expected) the target value is left unmodified and failbit
is set.
For example:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
struct coords
{
double X, Y, Z;
};
int main()
{
std::ifstream inf("data.poi");
std::vector<coords> verts;
std::string line;
while (std::getline(inf, line))
{
std::istringstream iss(line);
coords coord;
if (iss >> coord.X >> coord.Y >> coord.Z)
{
verts.push_back(coord);
}
else
{
std::cerr << "Could not process " << line << std::endl;
}
}
}
Upvotes: 6
Reputation: 2206
The same way you would do it for an integer with atoi.
For conversion from char* to double, simply use :
atof
Upvotes: 0