【问题标题】:Why does this leveldb code truncate "std::string"s that have spaces in them?为什么这个 leveldb 代码会截断其中有空格的“std::string”?
【发布时间】:2017-04-20 19:54:50
【问题描述】:

我写了这段代码来试试leveldb。我使用 Unix 时间作为键。对于包含空格的值,仅保存最后一部分。这是代码。我正在运行 Linux Kernel 4.4.0-47-generic

  while (true) {
    std::string note;
    std::string key;
    std::cout << "Test text here ";
    std::cin >> note;
    std::cout << std::endl;

    if(note.size() == 0 || tolower(note.back()) == 'n' ) break;
    key = std::to_string(std::time(nullptr));
    status = db->Put(write_options, key, note);

    if(!status.ok()) break;
  }

  std::cout << "Read texts........" << std::endl;
  leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
  for(it->SeekToFirst(); it->Valid(); it->Next()){
      std::cout << it->key().ToString() << "  " << it->value().ToString() << std::endl;
  }

  delete db;

【问题讨论】:

    标签: c++ c++11 leveldb


    【解决方案1】:

    问题不在于 leveldb,而在于您读取输入的方式:

    std::string note;
    std::cin >> note;
    

    这将只读取第一个空格。这是常见的错误,例如:

    reading a line from ifstream into a string variable

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-08
      • 2019-12-21
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      相关资源
      最近更新 更多