-2

I created a program which takes a 'word' and a num parameter as the shifting number. Example if the string is Caesar Cipher and num is 2 the output should be Ecguct Ekrjgt. But I want the punctuation, spaces, and capitalization to remain intact. Also I can't add a sentence. Just a word. I am not allowed to use strings.

#include<iostream>
using namespace std;

int main()
{
  char name[50] = { '\0' };
  int cipherKey, len;

  cout << "Enter cipher key: ";
  cin >> cipherKey;

  cout << "Enter a message to encrypt: ";
  cin >> name;

  len = strlen(name); // this code just inputs the length of a word. after spaces it won't calculate.

  for (int i = 0; i < len; i++)
  {
    char temp = name[i] + cipherKey;
    cout << temp;
  }
  cout << "\n\n";

  return 0;
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Hassan Yousuf
  • 751
  • 6
  • 12
  • 24

1 Answers1

1

To ignore punctuation, I would suggest that inside your for loop you should put an if to select the punctuation that you want to leave unchanged. For example:

for (int i = 0; i < len; i++)
{
    if( name[i]==' ' || name[i]==',' || name[i]=='.' /*...etc...*/ )
        cout << name[i];
    else {
        char temp = name[i] + cipherKey;
        cout << temp;
    }
}

It's a tedious to type it out for each special puctuation character, but c++ is kinda like that :P

To get the cipher working: as mentioned in comments, the line

char temp = name[i] + cipherKey;

will not always do what you expect. Specifically you will want to wrap around if name[i]+cipherkey is off the end of the alphabet. I'll leave that for you to figure out. (hint: google 'ASCII values' to see how a char is represented in number form)

Mike Ounsworth
  • 2,444
  • 21
  • 28