字符串流到具有未知分隔符的变量



我已经将一些数字转换为带有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 有什么简单的解决方案吗?

我可以推荐你这段代码吗?

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

最新更新