如何将字符串型位置转换为坐标型位置?

问题描述 投票:0回答:1

在我的工作中,读取了一个txt文件,其中的数据中有车辆的地理位置,由于我在读取这个文件的时候遇到了问题,我想把这些信息以字符串的形式读取,但是我需要把位置信息存储为坐标类型。由于我在读取这个文件的时候遇到了一个问题,我想把这些信息以字符串类型读取,但是我需要把位置信息以Coord类型存储。能否将字符串转换为Coord类型?

错误。

error: invalid operands to binary expression ('__istream_type' (aka 'basic_istream<char, std::char_traits<char> >') and 'veins::Coord')

当 "while() "把 "position "变量读成Coord类型时,就会出现错误。我认为比较简单的方法是将位置以字符串的形式获取,然后将其转换为Coord类型并存储在chData.position中。

所用方法的代码。

std::ifstream file;
    file.open("chFile.txt");

    if(file.is_open()) {

        int sector;
        int ch;
        Coord position;

        while (file >> sector >> ch >> position) {

            chTableStruct chData;
            chData.ch = ch;
            chData.position = position;

            chTable.insert(std::pair<int,chTableStruct>(sector,chData));

        }
        file.close();
    }
    else {
        std::cout << "The file chFile.txt cannot be opened! it exists?" << endl;
    }

chFile. txt文件

2 20 (401.467,223.4,0)
3 52 (201.446,223.4,0)
1 31 (201.461,623.4,0)
c++ veins
1个回答
2
投票

首先,对不起,我的英语不好... ...

当我需要读取一个字符串并转换为坐标时,在VEINS + OMNeT模拟器中我这样做。

Coord MyClass::strToCoord(std::string coordStr){
    //this 2 lines is will remove () if necessary
    coordStr.erase(remove(coordStr.begin(), coordStr.end(), '('), coordStr.end()); //remove '(' from string
    coordStr.erase(remove(coordStr.begin(), coordStr.end(), ')'), coordStr.end()); //remove ')' from string

    char coordCh[30]; //30 or a sufficiently large number
    strcpy(coordCh,coordStr.c_str());
    double x = 0, y = 0, z = 0;

    char *token = strtok(coordCh, ",");
    x = stold(token);
    token = strtok(NULL, ",");
    y = stold(token);
    token = strtok(NULL, ",");
    z = stold(token);

    cout << "x= " << x << ", y= " << y << ", z= " << z << endl; //comment this line to disable debugging

    return Coord(x,y,z);
}

但我不知道VEINS中是否已经有了这样的方法。

希望能帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.