c++使用string来存储float和int

标签 c++ string

假设现在我必须使用字符串传递一个 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/

相关文章:

c++ - 使用堆在堆栈中设置值

c++ - 如何修复未对齐的指针 (char**)

c++ - #include <string> 导致大量 '<blank>' has not been declared 错误

java - 如何在 Java 中比较字符串?

java - 使用哈希表检查单词的拼写

string - 我应该如何处理 D 中的 C 字符串?

python - 运行时错误 : Matching Python module for ImageSensor not found

c++ - 为什么 Apple 的 Clang(来自 Xcode 5)为 arm64 制作 typeinfos private_extern?

Javascript 使用 RegExp 替换字符串模式?

python - 如何根据位置替换字符串中多个相同的字符?