首页 > 解决方案 > 在 C++ 中实现 zip 和 unzip。我对 char* 缓冲区感到困惑

问题描述

下面的两个函数即将实现 zip 和 unzip,但是我在选择正确的类型缓冲区以保存文件中的字符串时遇到问题。

此外, forchar* ptr = line被声明为指向 string 的指针line,它返回一个错误。

解压缩功能是同样的问题。

错误 :error: 初始化时无法将 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} 转换为 'char*'

//zip function
int main(int argc, char*argv[])
{
  if(argc == 1){
    return 0;
  }
  string line;
  // char *line = new char[SIZE];
  for(int i = 1; i < argc; i++){
    ifstream file(argv[i]);
    if(file.fail()){
      cerr << "wzip: cannot open file" << endl;
      return 1;
    }
    while(getline(file,line)){
      char *ptr = line;
      char current = *ptr;
      unsigned int count = 0;
      while(*ptr){
        if(*ptr == current){
          count++;
          ptr++;
          continue;
        }else if(count == 4294967295){
          cout << count << current;
          current = 0;
          count = 0;
        }else{
          cout << count << current;
          current =*ptr;
          count = 0;
        }
      }
    }
    cout << endl;
    file.close();
  }
  return 0;
}
//unzip function
int main(int argc, char* argv[])
{
  if(argc == 1){
    return 0;
  }
  char buffer;
  for(int i = 1; i < argc; i++){
    ifstream file(argv[i]);
    if(file.fail()){
      cerr <<"wunzip: cannot open file" << endl;
      return 1;
    }
    while(getline(file,line)){
      char *ptr = buffer;
      unsigned int count = 0;
      while(*ptr != 0){
        if(*ptr <='9' && ptr >= 0){
          count = count*10+(*ptr-'0');
        }else{
          while(count--){
            cout << *ptr;
            count = 0;
          }
        }
        ptr++;
      }
    }
    cout << endl;
    file.close();
  }
  return 0;
}

标签: c++char

解决方案


这行是问题所在,因为它试图将 a 设置为char *等于 a std::string,这是不允许的操作(因为 astd::string是 C++ 对象,而不是原始字符数组):

char *ptr = line;

您可能想要更像这样的东西,它ptr指向line's 内部字符数组的开头:

const char *ptr = line.c_str();

(我添加const了类型,ptr因为您不允许写入 a 内部保存的字符数组std::string


推荐阅读