如何将char*作为双打?

Dea*_*ean 1 c++

我有一个结构,x,y,z为double类型.我试图用空格分割线条,然后将该数组的值放入我的结构但是它无法工作,有人可以告诉我该怎么做?

#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;
    }

}
Run Code Online (Sandbox Code Playgroud)

谢谢

Joh*_*web 6

你不能(有意义地) a转换char*为a double,但是你可以从流中提取成a double.

由于您在空格上分割输入行,因此典型的习惯用法就是这样...对于文件中的每一行,创建一个istringstream对象并使用它来填充您的结构.

如果operator >>()失败(例如,如果输入了预期数字的字母),则目标值保持不变并被failbit设置.

例如:

#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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)