首页 > C++截取字符串问题,如何在每段长度不确定的情况下去除自己想要的数据?

C++截取字符串问题,如何在每段长度不确定的情况下去除自己想要的数据?

如题,我想从一段字符串中取到我想要的几个数据:字符串如下

string str = "            vertex -517.403450012207 50 -555.422477722168";
//或者
string str1 = "     facet normal -0.9999999999999999 0 0";
//主要这两种类型

补充:字符串前面的空格个数不是固定的,有的时候多点有的时候少点而且有的时候是 \t 这个样子。但是字符串中间的空格都是固定的一个。

//我 还是贴一些代码
ifstream inOBJ;
    string fp;
    fp = "xxx.xxx”;文件地址
    inOBJ.open(fp);
    cout<<fp<<endl;
    if(!inOBJ.good())
    {
        printf("ERROR OPENING OBJ FILE");
        exit(1);
    }
    
    // Read OBJ file
    int count = 0;
    while(!inOBJ.eof())
    {
        string line;
        getline(inOBJ, line);
       //line = "上文贴出的字符串存在于这里";
         //欲在此处取到line里的三个float数
        cout<<count<<endl;
        count++;
        
    }

我想要的是字符串中后面的三个float数,并把他们存到数组里这样。
思路类似于trim掉字符串前段的空格后将剩余的字符串按空格分隔,再取到后面三个float这样。
小人只有上大学的时候看过点C,这种可能很基础的东西,自己却觉得很难,求助


void split(std::vector<std::string> & vector, const std::string & str, const std::string & pattern)
{
    std::string::size_type pos1, pos2;
    pos2 = str.find(pattern);
    pos1 = 0;
    while(std::string::npos != pos2)
    {
        vector.push_back(str.substr(pos1, pos2-pos1));

        pos1 = pos2 + pattern.size();
        pos2 = str.find(pattern, pos1);
    }
    if(pos1 != str.length()) {
        vector.push_back(str.substr(pos1));
    }
}

void ltrim(std::string & str)
{
    auto it2 = std::find_if( str.begin() , str.end() , [](char ch){
        return !std::isspace<char>(ch , std::locale::classic() ) ;
    });
    str.erase(str.begin(), it2);
    return str;
}

int main() {
    std::string str = "            vertex -517.403450012207 50 -555.422477722168";
    ltrim(str);
    std::vector<std::string> vector;
    split(vector, str, " ");
    for( auto i : vector){
        std::cout << i << std::endl;
    }
}
【热门文章】
【热门文章】