You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++凯撒密码代码报std::logic_error空值构造错误如何解决

问题原因
  • 核心报错原因:cipher、decipher两个函数声明的返回值类型为string,但函数末尾执行return 0,0会被隐式转换为空指针,触发std::string用空指针构造的逻辑错误,对应你收到的报错信息。两个函数仅负责直接输出结果,不需要返回字符串,返回值类型设计错误。
  • 附加bug1:cin >> type读取用户输入的加密/解密选项后,输入缓冲区会残留换行符,后续getline(cin, text)会直接读取到空内容,不会等待用户输入待处理文本。
  • 附加bug2:解密逻辑中字符减密钥可能得到负数,直接对26取模会得到负数值,最终输出乱码。
修复方案
  1. 将cipher、decipher的返回值类型改为void,删除函数末尾的return 0语句。
  2. 在cin >> type之后新增cin.ignore(),跳过缓冲区残留的换行符。
  3. 解密计算时先加26再取模,避免负数问题。
修复后完整代码
#include <iostream>
using namespace std;
// 修改返回值类型为void
void cipher(int key,string text);
void decipher(int key,string text);

int main(int argc, char** argv) {
   string type;
   string text;
   int key;

   if (argc != 2) {
       cout << "Usage ./caesar key" << endl;
       return 1;
   }
   string s = argv[1];
   for (int k = 0;k < s.length(); k++) {
       if (isalpha(argv[1][k]))
       {
           cout << "Usage: ./caesar key" << endl;
           return 1;
       }
   }
   cout << "Type c for cipher and d for decipher: ";
   cin >> type;
   cin.ignore(); // 跳过残留换行
   cout << "text: ";
   getline(cin, text);

   key = atoi(argv[1]);
   if (type == "c") {
      cipher(key,text);
   } else {
       decipher(key,text);
   }
   cout << endl;
   return 0;
}

void cipher(int key,string text) {
     for (int i = 0; i < text.length(); i++) {
        if (islower(text[i])) {
            char m = (((text[i] + key) - 97) % 26) + 97;
            cout << m;
        } else if(isupper(text[i])){
            char a = (((text[i] + key) - 65) % 26) + 65;
            cout << a;
        } else {
            cout << text[i];
        }
    }
}

void decipher(int key,string text) {
    for (int i = 0; i < text.length(); i++) {
         if (islower(text[i])) {
            // 加26避免负数
            char m = (((text[i] - key) - 97 + 26) % 26) + 97;
            cout << m;
        } else if(isupper(text[i])){
             char a = (((text[i] - key) - 65 + 26) % 26) + 65;
             cout << a;
        } else {
           cout << text[i];
        }
    }
}

内容的提问来源于stack exchange,提问作者srikar amirneni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 07:45:11