c++ - 为什么这个 leveldb 代码会截断其中有空格的 "std::string"?

标签 c++ c++11 leveldb

我写这段代码是为了试试leveldb。我使用 Unix 时间作为键。对于有空格的值,只保存最后一部分。这是代码。我正在运行 Linux 内核 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;

最佳答案

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

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

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

reading a line from ifstream into a string variable

关于c++ - 为什么这个 leveldb 代码会截断其中有空格的 "std::string"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40990918/

相关文章:

c++ - 为什么 vector 的多参数构造函数采用未标记为 "explicit"的构造参数?

c++ - 为什么要在levelDB的缓存中使用while循环(函数Resize)?

c++ - 调用函数和返回值

C++字符串表.res文件

c++ - 如何使用 std::tuple 的值作为参数调用函数?

leveldb - LMDB 是否支持多个键到相同值的映射?

ubuntu - Riak 节点因 I/0 错误而终止

c++ - 如何在 QMainWindow 中按下 Ctrl 时禁用滚动功能

c++ - 如何防止 Boost.Interprocess 使用 wchar?

c++ - 在 C++ 源文件中包含 C++11 头文件