字符串空格判断失效,无法为6位二进制段前添加0的技术求助
问题原因与解决办法
你的两段代码都卡在无限循环里了——每次调用insert都会让字符串长度增加2,而循环条件i < EightByte_BinaryBuffer.length()里的长度是动态增长的,i永远追不上不断变大的字符串长度,程序就一直跑停不下来。
给你两种可行的解决方式:
方式一:直接构建结果字符串
遍历原字符串,开头先加00,遇到空格后也追加00,避免修改原字符串导致的循环异常:
#include <iostream> #include <string> using namespace std; int main() { string input = "010000 010100 001001 000011"; string result; // 开头先补两个0 result += "00"; for (char c : input) { result += c; // 遇到空格,后面补两个0 if (c == ' ') { result += "00"; } } cout << result << endl; return 0; }
方式二:分割处理每个6位段
把原字符串按空格分割成独立的6位二进制段,给每个段前加00后再拼接,逻辑更清晰,适合Base64转换的场景:
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string input = "010000 010100 001001 000011"; stringstream ss(input); string segment; string result; while (ss >> segment) { if (!result.empty()) { result += " "; } // 给每个6位段前加00 result += "00" + segment; } cout << result << endl; return 0; }
两种方法都会输出预期结果:00010000 00010100 00001001 00000011,刚好满足你Base64转换中把6位二进制组转成8位的需求。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

