c++ - 当我尝试执行我的代码时,我保持错误“'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;
}
我该如何解决这个问题,当我只将其设为密码而不是破译时,它工作得很好。但当我试图破译它停止工作。
解决方案
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;
推荐阅读
- windows - % Processor Time 的单位是什么,它表示什么?
- command - 由命令触发的 Minecraft 事件处理程序
- mongodb - 使用空手道自动测试 MongoDB 的正确方法
- java - Hibernate 在使用查询缓存时执行 N+1 个选择而不是 1 个查询
- mysql - Sequelize findAll 不是函数 4
- r - 根据其他列中的值,在数据框中创建具有升序值的新列
- assembly - 如何从程序集调用 cobol 程序 (z/os IBM)
- amazon-web-services - 错误管道步骤“无服务器部署”显示“IamRoleLambdaExecution - 角色 XXXXX 的最大策略大小超过 10240 字节”
- bash - 如果第一列中的值匹配并且第二列中的值与bash中另一个文件中的值不匹配,则提取行
- oracle - 我无法删除 sqlplus 中的所有表