【问题标题】:Getting an error in my C++ CaesarCipher Program在我的 C++ CaesarCipher 程序中出现错误
【发布时间】:2017-10-25 11:23:00
【问题描述】:

我正在尝试在 C++ 中创建凯撒密码,但在尝试构建程序时不断收到此错误,有什么帮助吗? 我收到的错误如下:

在抛出 'std::logic_error' 实例后调用终止
what(): basic_string::_M_construct null 无效中止(核心 倾倒)

代码如下:

#include <stdio.h> 
#include <iostream>
#include <string>

using namespace std;

string caesarCipher(string text, int ciphe);

int main(void)  {
string text, encodedString; 
int ciphe = 0;
cout << "Please enter a word: ";
getline(cin, text);
cout << "Key: ";
cin >> ciphe;

encodedString = caesarCipher(text, ciphe);
cout <<"Encrypted: " << encodedString << "\n";

return 0;
}

string caesarCipher(string text, int ciphe)
{
string temp = text;
int length;

length = (int)temp.length();

for (int i = 0; i < length; i++)
{
      if(isalpha(temp[i]))
      {
        for (int x = 0; x < ciphe; x++)
        {
          if (temp[i] == 'z')
          {
              temp[i] = 'a';
          }
          else
          {
            temp[i]++;
          }
        }
      }
    }

    return 0;
}

【问题讨论】:

  • 程序构建(或编译)正确,但不能正确运行

标签: c++ error-handling


【解决方案1】:

实际上,这段代码我没有遇到任何编译错误,只是caesarCipher 例程中有一个小错误。

您必须实际返回 temp 字符串而不是 0 才能获得正确答案。

正确的代码应该是

string caesarCipher(string text, int ciphe)
{
string temp = text;
int length;

length = (int)temp.length();

for (int i = 0; i < length; i++)
{
      if(isalpha(temp[i]))
      {
        for (int x = 0; x < ciphe; x++)
        {
          if (temp[i] == 'z')
          {
              temp[i] = 'a';
          }
          else
          {
            temp[i]++;
          }
        }
      }
    }

    return temp;
}

【讨论】:

    【解决方案2】:

    您的代码没有遇到任何编译错误。它在我的机器上编译成功,我还与 ideone 进行了交叉检查。它正在正确编译。

    在函数末尾添加return temp;语句而不是return 0;

    检查这里-http://cpp.sh/5eo2r

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多