Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 最后一个符号在LZW中重复_C++_Lzw - Fatal编程技术网

C++ 最后一个符号在LZW中重复

C++ 最后一个符号在LZW中重复,c++,lzw,C++,Lzw,我尝试实现LZW编码/解码,最终得到以下代码 #include <cstdint> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <unordered_map> using Index = std::int16_t; void encode(std::istream &input, std:

我尝试实现LZW编码/解码,最终得到以下代码

#include <cstdint>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>

using Index = std::int16_t;

void encode(std::istream &input, std::ostream &output) {
  Index index{0};
  std::unordered_map<std::string, Index> dictionary{};

  for (int i = 0; i < 256; ++i) {
    dictionary[{static_cast<char>(i & 0xFF)}] = index++;
  }

  char k;
  input.read(&k, sizeof(char));
  std::string buffer{""};
  while (input) {
    const auto tmp = buffer + k;
    if (dictionary.contains(tmp))
      buffer = tmp;
    else {
      dictionary[tmp] = index++;
      output.write(reinterpret_cast<const char *>(&dictionary[buffer]),
                   sizeof(Index));
      buffer = {k};
    }
    input.read(&k, sizeof(char));
  }
  output.write(reinterpret_cast<const char *>(&dictionary[buffer]),
               sizeof(Index));
}

void decode(std::istream &input, std::ostream &output) {
  Index index{0};
  std::unordered_map<Index, std::string> dictionary{};

  for (int i = 0; i < 256; ++i) {
    dictionary[index++] = {static_cast<char>(i & 0xFF)};
  }

  Index k;
  input.read(reinterpret_cast<char *>(&k), sizeof(Index));
  output << dictionary[k];

  Index old{k};
  std::string buffer;
  while (input) {
    input.read(reinterpret_cast<char *>(&k), sizeof(Index));
    buffer = dictionary[old];

    std::string tmp;
    if (dictionary.contains(k)) {
      const auto &entry = dictionary[k];
      tmp = buffer + entry.front();
      output << entry;
    } else {
      tmp = buffer + buffer.front();
      output << tmp;
    }
    dictionary[index++] = tmp;
    old = k;
  }
}

输出<代码>你好,世界而不是
你好,世界。我找不到我的错误,也许其他人可以?

正如@NathanOliver在评论中指出的那样 将解码循环更改为

while (input.read(reinterpret_cast<char *>(&k), sizeof(Index))) { 
while(input.read(reinterpret_cast&k),sizeof(Index)){

修复它。

相关/重复:循环在
encode
中是正确的(虽然可能不是惯用法),但在
decode
中是不正确的。在同一个程序中,看到此错误非常常见,但看不到正确和错误的输入循环。
while (input.read(reinterpret_cast<char *>(&k), sizeof(Index))) {