首页 > 解决方案 > 当我尝试执行我的代码时,我保持错误“'std::logic_error'what(): basic_string::_M_construct null not valid”

问题描述

我正在制作一个密码代码,当我尝试执行它时,我得到“std::logic_error'what(): basic_string::_M_construct null not valid”。代码有什么问题。

#include <iostream>
using namespace std;
string cipher(int key,string text);
string decipher(int key,string text);

int main(int argc, char** argv) {
   string type;
   string text;
   string dtext;
   char* key1;
   int key;
   string s = argv[1];

   if (argc != 2) {
       cout << "Usage ./ceaser key" << endl;
       return 1;
   }

   else {
        for (int k = 0;k < s.length(); k++) {

           if (isalpha(argv[1][k]))
           {
               cout << "Usage: ./caesar key" << endl;
               return 1;
           }
           else
           {
               continue;
           }
       }

   }
   cout << "Type c for cipher and d for decipher: ";
   cin >> type;
   cout << "text: ";
   getline(cin, text);

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


}

string 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];
        }
    }
    return 0;
}

string decipher(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];
        }
    }
    return 0;
}

我该如何解决这个问题,当我只将其设为密码而不是破译时,它工作得很好。但当我试图破译它停止工作。

标签: c++

解决方案


string cipher(int key,string text) {
    ...
    return 0;
}

如果返回值的类型不正确,则 return 语句应用返回类型的适当构造函数。在这种情况下std::string::string(const char*)使用并传递空指针导致问题。您需要在此处返回加密结果,而不是将结果打印到标准输出。(在 中相应地进行decypher。)

在这种情况下,与我的评论相反,您实际上可以通过复制传递值以便能够修改字符串并返回它:

...
if (islower(text[i])) {
    //char m = (((text[i] + key) - 97) % 26) + 97;
    //cout << m;
    text[i] = (((text[i] + key) - 97) % 26) + 97;
}

...
return text;


推荐阅读