Sorry, the assignment was to use a string. Here is my code. I am stuck. I do not know why it aborts after the 'h' in "This is C++!". I am not finished yet. This is my draft.
I made the change to the Boolean expression in the while statement. I subtracted 'A' and 'a' from cstr[incr] in the upper and lower case if statements, respectively I did not add them back because I am not ready to decipher the string.
I am still getting a Debug Assertion Failure: string substring out or range.
/*
* ceasar
*
* Get the key
* Get the plaintext
* Encipher the text
One character
Entire plaintext
isapha
isupper
islower
* Print cipher text message
* Start: ASCII values
* Encipher: Alphabetical index
* Print: ASCII values
*
* c[i] = (p[i] + k) % 26
*
*/
#include <cstdio> // printf_s scanf_s
#include <cstdlib> // atoi
#include <cctype> // isupper, islower
#include <iostream> // cin, cout
#include <string> // getline
usingnamespace std;
int main(int argc, char* argv[])
{
// error check
if (argc != 2)
{
printf("Illegal Usage: ./ascimath key");
return 1;
}
// key is the second command line argument and is converted from char to integer
int key = atoi(argv[1]);
// variable
string cstr ("This is C++!");
string dest( cstr.size(),'x' );
int incr = 0;
// Get message from user
// printf_s("Enter the message: ");
// printf_s("%i\n", cstr);
// getline(cin, cstr);
int len = cstr.length();
printf("len is: %i\n", len);
while (incr < len)
{
cout << "working character: " << cstr[incr] << endl;
// encrypt message
if (isupper(cstr[incr]) != 0)
{
// change ASCII value to encrypt value
int x = (cstr[incr] - 'A' + key) % 26;
printf("x in isupper is: %i\n", x);
dest[incr] = x + 'A';
}
elseif (islower(cstr[incr]) != 0)
{
int x = (cstr[incr] - 'a' + key) % 26;
printf("x in islower is: %i\n", x);
dest[incr] = x + 'a';
}
else
{
dest[incr] = cstr[incr];
}
incr++;
printf("incr is %i\n", incr);
}
// Print encrytion.
for (int i = 0; i < len; i++)
{
printf("%c", dest[i]);
}
}
Output in Linux UBUNTU:
abhishekm71@PC:~$ ./temp 2
len is: 12
working character: T
x in isupper is: 21
incr is 1
working character: h
x in islower is: 9
incr is 2
working character: i
x in islower is: 10
incr is 3
working character: s
x in islower is: 20
incr is 4
working character:
incr is 5
working character: i
x in islower is: 10
incr is 6
working character: s
x in islower is: 20
incr is 7
working character:
incr is 8
working character: C
x in isupper is: 4
incr is 9
working character: +
incr is 10
working character: +
incr is 11
working character: !
incr is 12
Vjku ku E++!
EDIT: dest string initialized to match the length of cstr.
I copied your code and pasted it into Visual Studio 2013 Express and got the same Debug Assertion Failure. I have revised my code since then and will post it under a different subject.