假设现在我必须使用字符串传递一个 struct foo。该结构包含 3 个部分: 一个整数,一个 float 和一个字符串:
struct foo {
int a;
float b;
string c;
}
我决定做的是编写一个简单的包装器来编码和解码这个结构 foo:
string& encode_foo(const foo &input) {
// what do I do here?
// declare a string and fill in 4 bytes for a, 4 bytes for b and then c?
string ret;
ret.append((char*)(&input.a), 4); // This is really ugly, isn't it??
ret.append((char*)(&input.b), 4); // this is also very ugly??
}
foo decode_foo(const string &input) {
// get input.c_str() and cast to int and float?
}
我很好奇是否有一种优雅的方式来做到这一点?
最佳答案
也许是这样的:
struct foo {
int a;
float b;
string c;
}
std::ostream& operator<<(std::ostream& os, const foo& f) {
return os << f.a << " " << f.b << " " << f.c;
}
std::istream& operator>>(std::istream& is, foo& f) {
return is >> f.a >> f.b >> f.c;
}
std::string encode(const foo& f) {
std::ostringstream oss;
oss << f;
return oss.str();
}
std::string decode(const std::string& s) {
std::istringstream iss( s );
foo f;
iss >> f;
return f;
}
int main() {
foo f;
std::string s=encode(f);
f=decode(s);
}
这样做的好处是:
- 它惯用,一个众所周知的模式
- 它还允许您轻松打印对象的值,
std::cout << f
关于c++使用string来存储float和int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15120448/