c++ - 在 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;
}
解决方案
这行是问题所在,因为它试图将 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
)
推荐阅读
- woocommerce - WP API 挂钩的 Woocommerce POST 请求不起作用
- azure - 如何通过 ARM 更新 Azure 服务总线的队列/主题?
- sqlite - 如何在选择中使用 SQLite db 文件位置?
- android - BleCharacteristicNotFoundException:未使用 UUID 找到特征。如何从蓝牙设备获取特征 UUID?
- ios - UICollectionViewCell 中的 iOS UIScrollView
- c++ - C++ 枚举类:强制转换为不存在的条目
- ios - 在 swift4 中使用 NSTimer 处理 UIPagecontrol
- shell - 需要使用 Unix shell 脚本在每行末尾添加空格
- angular - 延迟加载模块中的角度使用服务
- php - 数组上的“dump()”将显示的最大项目数?