所以,我正在编写一个运行长度解码器来练习我的C++技能,当我试图构建和测试我的RLE程序时,我收到了这个错误:
44 | std::stringstream dig(next);
| ^~~~
| |
| char
In file included from src/rle.cpp:3:
/usr/include/c++/9/sstream:756:45: note: initializing argument 1 of 'std::__cxx11::basic_stringstream<_CharT, _Traits, _Alloc>::basic_stringstream(std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::ios_base::openmode = std::_Ios_Openmode]'
756 | basic_stringstream(ios_base::openmode __m)
| ~~~~~~~~~~~~~~~~~~~^~~
make[2]: *** [CMakeFiles/cpp-rle.dir/build.make:63: CMakeFiles/cpp-rle.dir/src/rle.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:112: CMakeFiles/cpp-rle.dir/all] Error 2
make: *** [Makefile:141: all] Error 2现在我不是很擅长C++,但是我知道在尝试将str的子串转换成整数std::stringstream dig(next);时会出现问题,但是我还不够精通,无法理解为什么这会返回一个错误。
#include "rle.hpp"
#include <iostream>
#include <sstream>
std::string run_length_encode(const std::string& str)
{
std::string encoded_string = "";
char prev;
char next;
int count = 1;
prev = str[0];
for (int i = 0; i < str.length(); i++){
next = str[i];
if (prev == next){count++;}
else{
encoded_string += prev;
if(count > 1){
encoded_string += std::to_string(count);
}
prev=next;
count=1;
}
}
if (prev == next){
encoded_string += next;
if (count > 1){
encoded_string += std::to_string(count);
}
}
return {encoded_string};
}
std::string run_length_decode(const std::string& str)
{
// Implement!
std::string decoded_string = "";
char prev;
char next;
int count = 0;
prev = str[0];
for (int i = 0; i < str.length(); i++){
next = str[i];
if (isdigit(next)){
prev = str[i - 1];
std::stringstream dig(next);
dig >> count;
for (int j = 1; j < count; j++){
decoded_string += prev;
}
}
else{ decoded_string += next; }
}
return { decoded_string };
}我发布了我的整个程序以及错误,以便提供关于我的代码的所有重要信息。下面也是我的输入和预期输出的示例,以便您了解我试图返回的内容。
Encoding:
WWWABC should be replaced with W3ABC.
WWWWBBWWWWW should be replaced with W4B2W5.
Decoding:
W3ABC should be replaced with WWWABC .
W4B2W5 should be replaced with WWWWBBWWWWW.发布于 2020-04-24 00:09:34
为此,您不需要使用stringstreams。这整个逻辑
if (isdigit(next)){
prev = str[i - 1];
std::stringstream dig(next);
dig >> count;
for (int j = 1; j < count; j++){
decoded_string += prev;
}
}可以替换为:
if (isdigit(next)){
decoded_string += std::string(next - '0', str[i - 1]);这只使用了string构造器,该构造器构造了长度为n的重复字符的字符串。
发布于 2020-04-24 00:07:02
next是一个字符。您不能从单个字符中获取字符串流。您可能需要:
count = next - '0';如果可以确定,在这一点上,next位于'0'和'9'之间。
https://stackoverflow.com/questions/61391704
复制相似问题