stringstream到具有未知分隔符的变量

时间:2017-09-14 12:50:11

标签: c++ stringstream

我已将一些数字转换为带有string类型的分隔符的字符串,如下所示

#include <sstream>
#include <string>
#include <iostream>

std::string vars_to_string(std::string separator, double object_x, double object_y, double object_z, std::string msg) {
  std::stringstream ss;
  ss << msg << separator;
  ss << object_x << separator;
  ss << object_y << separator;
  ss << object_z;
  return ss.str();
}

void string_to_vars(std::string text, std::string separator, double &object_x, double &object_y, double &object_z, std::string &msg) {
  // ????????
}

int main() {
  double x = 4.2, y = 3.7, z = 851;
  std::string msg = "position:";
  std::string text = vars_to_string("__%$#@!__", x, y, z, msg);
  std::cout << text << std::endl;

  double rx, ry, rz;
  std::string rmsg;
  string_to_vars(text, "__%$#@!__", rx, ry, rz, rmsg);
  std::cout << "Retrived data: " << rx << ", " << ry << ", " << rz << ", " << rmsg << std::endl;
  return 0;
}

现在,我想知道如何反过来将结果变量再次转换为msgobject_xobject_yobject_z

要停止建议简单的解决方案,我使用__%$#@!__作为分隔符。分隔符由用户决定,它可以是任意值,代码不应该失败。

我不假设object_x是纯数字。我只假设它不包含分隔符。

我们不知道分隔符。

有没有使用Boost的简单解决方案?

问题很清楚。如果有任何问题,请另外询问,请重新打开问题

1 个答案:

答案 0 :(得分:1)

我可以建议你这段代码吗?

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

void dtokenize(const std::string& str, std::vector<std::string>& tokens, const std::string& separator)
{
    std::string::size_type pos = 0;
    std::string::size_type lastPos = 0;

    while(std::string::npos != pos) {
        // find separator
        pos = str.find(separator, lastPos);

        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));

        // set lastpos
        lastPos = pos + separator.size();
    }
}

std::string vars_to_string(std::string separator,double object_x, double object_y, double object_z, std::string msg)
{
    std::stringstream ss;
    ss<<msg<<separator;
    ss<<object_x<<separator;
    ss<<object_y<<separator;
    ss<<object_z;
    return ss.str();
}

void string_to_vars(std::string text,std::string separator,double &object_x, double &object_y, double &object_z, std::string &msg)
{
    vector<string> vars;
    dtokenize(text, vars, separator);

    if(vars.size() == 4) {
        msg = vars[0];
        object_x = stod(vars[1]);
        object_y = stod(vars[2]);
        object_z = stod(vars[3]);
    }
}

int main()
{
    double x=4.2,y=3.7,z=851;
    std::string msg="position:";
    std::string text=vars_to_string("__%$#@!__",x,y,z,msg);
    std::cout<<text<<std::endl;

    double rx,ry,rz;
    std::string rmsg;
    string_to_vars(text,"__%$#@!__",rx,ry,rz,rmsg);
    std::cout<<"Retrived data: "<<rx<<", "<<ry<<", "<<rz<<", "<<rmsg<<std::endl;

    return 0;
}