I am creating a vigenere cipher in c++ and when i run the code it has an error says: (Press Retry to debug the application) ConsoleApplication2.exe has triggered a breakpoint. Debug Assertion Failed! Program: C:\Windows\system32\MSVCP140D.dll File: c:\program files (x86)\microsoft visual studio 14.0\vc\include\xstring Line: 1681 Expression: string subscript out of range For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts. (Press Retry to debug the application) ConsoleApplication2.exe has triggered a breakpoint. The program '[3668] ConsoleApplication2.exe' has exited with code -1073741510 (0xc000013a). here is the code:
#include <iostream>
#include <string>
#include "stdafx.h"
using namespace std;
int main()
{
string plaintext, key, Result;
int k = 0;
cout << "Enter the plain text: ";
cin >> plaintext;
cout << "Enter the key word: ";
cin >> key;
for (int i=0; i<plaintext.length(); i++)
{
Result[i] = (((plaintext[i] - 97) + (key[k] - 97)) % 26) + 97;
k++;
if (k == 6)
(k = 0);
}
cout << " \n\n\n";
for (int i=0; i<plaintext.length(); i++)
cout <<" "<< Result[i];
cout << "\n\n\n\n";
return 0;
}
The error is in the for statement for (int i=0; i<plaintext.length(); i++)
it says something about the < sign and I don't know why. Any help? Thanks :)
You never set a size for Result
so any i
you use in
Result[i] = (((plaintext[i] - 97) + (key[k] - 97)) % 26) + 97;
is invalid. You need to first set a size for Result
. You could use something like
string plaintext, key, Result;
int k = 0;
cout << "Enter the plain text: ";
cin >> plaintext;
cout << "Enter the key word: ";
cin >> key;
Result.resize(plaintext.size());
//...
In the statement
key[k]
How do you check that the index k < key.length()
? The variable k
is bounded in [0,5] but how do you know that `key.length() < 5'?
User contributions licensed under CC BY-SA 3.0