alphabet encryption program - c++

Hi I am working on an encryption program. The program should take a letter inputted by the user and replace it with the corresponding letter 11 places further down the alphabet. For example, if the user inputs "joe" the program should output "uzp".
My current code does this fine but it doesn't recognise spaces and the program should wrap-around the alphabet. So that'Y' becomes 'J' and 'Z' would become 'K' etc. Anyone know how I could fix this?
void encrypt(std::string &e);
int main() {
string nameAttempt;
cout << "Enter your name to be Encrypted: ";
cin >> nameAttempt;
cout << "Original string is: " << nameAttempt << endl;
encrypt( nameAttempt );
cout << "Encrypted string is: " << nameAttempt << endl;
system("pause");
return 0;
}
void encrypt (std::string &e) {
const char* tempCharArray = e.c_str();
for( int i=0; i<e.size(); ++i )
e[i] = tempCharArray[i]+11;
} //

Assuming that you want to:
Replace lower-case letters with lower-case letters
Replace upper-case letters with upper-case letters
Leave spaces and any other non-alphabetic characters as is
void encrypt (std::string &e)
{
int size = e.size();
for (int i=0; i<size; i++)
{
char c = e[i];
if (('A' <= c && c <= 'Z'-11) || ('a' <= c && c <= 'z'-11))
e[i] = c+11;
else if ('Z'-11 < c && c <= 'Z')
e[i] = c+11-'Z'+'A';
else if ('z'-11 < c && c <= 'z')
e[i] = c+11-'z'+'a';
}
}

You could do something like this:
char _character='X';
int _value=static_cast<int>(_character);
if(_value!=32)//not space
{
int _newValue=((_value+11)%90);
(_newValue<65)?_newValue+=65:_newValue+=0;
char _newCharacter=static_cast<char>(_newValue);
}

Related

Maximum number of vowels in a word in string array

I have written a program to input 2 strings in a string array.
And then print the maximum vowels stored in the list.
Where am i going wrong here,and is there a more elegant method to this.
#include<iostream.h>
#include<string.h>
int main()
int i,j,c=0,k=0,maxo=0,len1,maxo1=0,len3;
char vow[] = "AEIOUaeiou";
char list[100][100],vow[]={"AEIOUaeiou"};
for(i=0;i<2;i++) {
cout<<"Enter word: ";
gets(list[i]);
for(i=0;i<2;i++) {
len1=strlen(list[i]);
for(k=0;k<len1;k++) {
for(j=0;list[j][k]!='\0';j++)
if(list[j][k]==vow[j])
c++;
}
if(c>maxo)
maxo=c;
c=0;
}
cout<<"Maximum Vowel count:"<<maxo<<endl;
}
fflush(stdin);
getchar();
return 0;
}
The bigger programme where i am trying to incorporate this code.The necessary comments are in the code.I really cannot undertand where i am going wrong in the last part.
Should i include the last bit of code at first so that the program works?
#include<iostream.h>
#include<string.h>
int main()
{
int i,n,len=0,sum=0,j,max,min,c=0,c2=0,k=0,maxo=0,len1,maxi=0,c1=0,len2;
float avg;
char list[100][100] = { 0 };
char vow[] = "AEIOUaeiou";
for(i=0;i<2;i++)
{
cout<<"Enter word: ";
gets(list[i]);
len=strlen(list[i]);
sum=sum+len;
cout<<"Length of word: "<<len<<endl;
if(list[i][len-1]=='s')
{cout<<"The Word "<<list[i]<<" ends with s"<<endl;
c2++;
}
}
//Word input by user.Prints word along with length.
min=strlen(list[0]);
max=strlen(list[0]);
//Initialising max and min.
for(i=0;i<2;i++)
{
if(strlen(list[i])<min)
{min=strlen(list[i]);}
if(strlen(list[i])>max)
{max=strlen(list[i]);}
}
for(i=0;i<2;i++)
{
if(max==strlen(list[i]))
cout<<"The max value of the lengths stored:"<<list[i]<<endl<<"Word count:"<<max<<endl;
if(min==strlen(list[i]))
cout<<"The min value of the lengths stored:"<<list[i]<<endl<<"Word count:"<<min<<endl;
}
//Max and Min value of string lengths are printed.
avg=sum/2;
cout<<"Avg length:"<<avg<<endl;
//Average value printed.
cout<<"The number of words with s:"<<c2<<endl;
//Word ending with s.
{for (i = 0; i <2; i++)
len1 = strlen(list[i]);
for (k = 0; k < len1; k++)
{
for (j = 0; j < strlen(vow); j++)
//if (list[j][k] == vow[j])
if (list[i][k] == vow[j])
c++;
}
cout << "Number of vowels in line " << i << ": " << c << '\n';
if (c>maxo) maxo = c;
c = 0;
cout << "Maximum Vowel count so far:" << maxo << "\n\n";
cout << "Maximum Vowel count:" << maxo << endl;
}
for(i = 0 ;i < 2 ;i++)
{ len3 = strlen(list[i]);
letter = list[i][0];
{for(j=0;j<len3;j++)
if(list[i][j]==letter)
counter++;
}
cout << "Number of identical letters as first letter in line " << i << ":
" << counter << '\n';
if (c>maxo1) maxo1 = counter;
counter = 0;
cout << "Maximum letter count so far:" << maxo1 << "\n\n";
cout << "Maximum letter count:" << maxo1 << endl;
}
PS:
I have edited my code one more time to display the alphabet which has occurred the maximum number of times as starting letter of a word in the list,and the number of times it has occurred.
This won't compile for me for two reasons:
1) gets()
The most recent revision of the C standard (2011) has definitively
removed this function from its specification. The function is
deprecated in C++ (as of 2011 standard, which follows C99+TC3).
And so I can't use the gets() function.
2) You can't declare
char list[100][100], char vow[] = {"AEIOUaeiou"};
both with a comma separator.
You read the input for the first line string into the first row of the array i = 0; then you instantly loop through i, which doesn't make sense. The following is not a good solution as in C++ you should be using std::vectors and std::string, and not generally mixing C and C++ but I've tried to keep it as close to your version, using my telepathic powers to read your mind about what you're trying to do.
#include <iostream>
#include <cstring>
using namespace std;
const int numLinesToGet = 10;
const int maxCharsPerLine = 100;
int main()
{
int i, j, c = 0, k = 0, maxo = 0, len1;
//char list[100][100], char vow[] = {"AEIOUaeiou"};
char list[100][100] = { 0 };
char vow[] = "AEIOUaeiou";
//for (i = 0; i < 2; i++)
for (i = 0; i < numLinesToGet; i++)
{
cout << "Enter word: ";
std::cin.getline(list[i], maxCharsPerLine);
//gets(list[i]);
//for (i = 0; i < 2; i++) Get rid of this second loop entirely
len1 = strlen(list[i]);
for (k = 0; k < len1; k++)
{
//for (j = 0; list[j][k] != '\0'; j++)
for (j = 0; j < sizeof(vow); j++)
//if (list[j][k] == vow[j])
if (list[i][k] == vow[j])
c++;
}
cout << "Number of vowels in line " << i << ": " << c << '\n';
if (c>maxo) maxo = c;
c = 0;
cout << "Maximum Vowel count so far:" << maxo << "\n\n";
}
cout << "Maximum Vowel count:" << maxo << endl;
fflush(stdin);
getchar();
return 0;
}
Online example here
#include<stdio.h>
int main ()
{
char a[] = "i love to code in education";
int i, count = 0, vow = 0, mvow = 0;
for (i = 0; a[i] != '\0'; i++)
{
if (a[i] == 'a' || a[i] == 'e' || a[i] == 'i' || a[i] == 'o'
|| a[i] == 'u')
{
vow++;
}
if (a[i]==' ')
{
count++;
mvow = vow;
vow = 0;
}
}
printf ("Total words: %d\n", count+1);
if(vow>mvow) printf ("Max Vowels in a word: %d", vow);
else printf("Max Vowels in a word: %d", mvow);
return 0;
}

Printing triangle with given letter in C++

I would like to to print a triangle with a given letter. For example, if I input D, the program should return:
A
AB
ABC
ABCD
So far, I have managed to print all letters until the given one in my example, but as you see this method is not quite effective since I need to do this for all 26 cases since the English alphabet is 26 chars. Is there some way to optimize my code?
#include <iostream>
using namespace std;
int main() {
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
if (65 < c) {
cout << "A";
cout << endl;
}
if (66 < c) {
cout << "AB";
cout << endl;
}
if (67 < c) {
cout << "ABC";
cout << endl;
}
for (int i = 64; i < c; i++) {
cout << static_cast<char>(i + 1);
}
return 0;
}
You definitely need to work on your comprehension of loops. This one works just fine and it even has some checks on what is typed in and it eventually converts lower case letters into upper casse.
char first = 'A';
char last = 0;
cout << "Enter a char: ";
cin >> last;
fflush(stdin);
cout << "\n\n";
if ((last > 96) && (last < 123)) //97 to 122 are lower case letters
{
last -= 32; //32 is the delta between each lower case letter and its upper case "twin"
}
if ((last > 64) && (last < 91))
{
for (char i = 65; i <= last; i++)
{
for (char j = 65; j <= i; j++)
{
cout << j;
}
cout << "\n";
}
}
else
{
cout << "\nWrong character!!\n\n";
return 0;
}
Use a nested loop structure. Use the outer loop to 'walk' down your triangle,
lineLength = 1;
while(lineLength <= (c - 64)){
...stuff...
lineLength++;
cout << endl;
}
Use the inner loop to 'walk' down the alphabet (you've already done most of this):
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
Putting it together:
lineLength = 1;
while(lineLength <= (c - 64)){
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
lineLength++;
cout << endl;
}
I see that someone else has posted a similar answer. Between these two answers, you should be able to find your way. I haven't compiled and run this code, but I believe that it should work or be very close.
Don't harcode ascii integer values into code. Explicitly use the character or string literals (e.g. 'A' instead of 65)
Start with a helper function to print exactly one line
// prints all the characters of the alphabetic sequence from "A" to the final char designated by <c>
void printTriangleLine(char c)
{
if ((c < 'A') || (c > 'Z'))
{
return;
}
for (char x = 'A'; x <= c; x++)
{
cout << x;
}
cout << endl;
}
Then put it all together in your main:
int main()
{
char i;
cout << "Enter char ";
cin >> i;
if ((i < 'A') || (i > 'Z'))
{
return 0;
}
for (char x = 'A'; x <= i; x++)
{
printTriangleLine(x);
}
return 0;
}
We must run the loop from position is above 'A' character
until we reached the charanter you enter
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
in each loop we increment character value by 1 to go to the next value
// go to next letter
chNew++;
inner loop simply print the character from A to next value relative to current chNew + 1, it is because we also want to include current character to our printed line.
Here is your working code.
#include <iostream>
using namespace std;
int main()
{
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
// start with 'A' - 1 character
char chNew = 'A' - 1;
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
// we have done
return 0;
}

Having trouble grasping simple boolean loop if/else program in C++

I need a little help figuring out a couple of parts from a C++ assignment. I am asked to write a program as follows:
Write a program that accepts input from the keyboard (with the input
terminated by pressing the Enter key) and counts the number of letters (A-Z and a-z), numerical digits (0-9), and other characters. Input the string using cin and use the following looping structure to examine each character in the string with an "if" statement and multiple "else if" statements.
char s[50];
int i;
. . .
i = 0;
while (s[i] != 0) { // a string is terminated with a null (0) value
. . .
i++;
}
Your program should make use of the relational operators (e.g., == < > <= >= !=) to determine whether a particular character is a letter, number, or other character. You may only #include and
may not use any other include files.
The program should have an output similar to the following:
Enter a continuous string of characters with no blank spaces (example: aBc1234!##$%)
enter your string: aBc1234!##$%
your string has 12 total characters
3 letters
4 numerical characters
5 other characters
Here is an example program that counts lower case letters:
// PROG07.CPP example
#include <iostream>
using namespace std;
int main()
{
char s[50];
int i;
int lowercase = 0;
//get string from the user
cout << "Enter a continuous string of characters with no blanspaces\n"
cout << "(example: aBc1234!##$%)" << endl << endl;
cout << "Enter your string: ";
cin >> s;
cout << endl;
// loop through the string, lower case letters
// note, strings (character arrays) have an invisible
// zero value at their end
i = 0;
while (s[i] != 0) // while the character does not have ASCII code zero
{
if ((s[i] >= 'a' && s[i] <= 'z'))
lowercase++;
i++;
}
cout << "Your string has " << lowercase << " lower case letters" << endl;
// including the next line for Dev-C++:
system("pause"); // not needed for CodeBlocks
return 0;
}
So far, I have come up with this:
#include <iostream>
using namespace std;
int main()
{
char s[50];
int i;
int lowercase, uppercase, numChars, otherChars = 0;
cout << "Enter a continuous string of characters" << endl;
cout << "(example: aBc1234!##$%)" << endl;
cout << "Enter your string: ";
cin >> s;
cout << endl;
while (s[i] != 0) // while the character does not have ASCII code zero
{
if ((s[i] >= 'a' && s[i] <= 'z'))
lowercase++;
i++;
}
while (s[i] != 0)
{
if ((s[i] >= 'A' && s[i] <= 'Z'))
uppercase++;
i++;
}
cout << lowercase + uppercase << " letters" << endl;
i = 0;
while (s[i] != 0)
{
if ((s[i] >= '0' && s[i] <= '9'))
numChars++;
i++;
}
cout << numChars << " numerical characters" << endl;
return 0;
}
Any help would be greatly appreciated.
You have to reset i to 0 before every loop:
#include <iostream>
using namespace std;
int main()
{
char s[50];
int i;
int lowercase, uppercase, numChars, otherChars = 0;
cout << "Enter a continuous string of characters" << endl;
cout << "(example: aBc1234!##$%)" << endl;
cout << "Enter your string: ";
cin >> s;
cout << endl;
i = 0; //missing
while (s[i] != 0) // while the character does not have ASCII code zero
{
if ((s[i] >= 'a' && s[i] <= 'z'))
lowercase++;
i++;
}
i = 0; // missing
while (s[i] != 0)
{
if ((s[i] >= 'A' && s[i] <= 'Z'))
uppercase++;
i++;
}
cout << lowercase + uppercase << " letters" << endl;
i = 0;
while (s[i] != 0)
{
if ((s[i] >= '0' && s[i] <= '9'))
numChars++;
i++;
}
cout << numChars << " numerical characters" << endl;
return 0;
}
Looks good so far, just a few things
First off, you only need the one while loop:
while (s[i] != 0)
{
//All your if checks can go in here
}
Then, according to the output you need, you will need 4 variables:
int total, lettters, numbers, otherCharacters;
At the start of your loop, add to total:
while (s[i] != 0)
{
total++;
}
Then you will need 3 if checks inside your while loop, one for letters, one for numbers, and one for other characters:
if ((s[i] > 'a' && s[i] < 'z') || (s[i] > 'A' && s[i] < 'Z')) { ... }
else if (s[i] > '0' && s[i] < '9') { ... }
else { ... }
Then just output all your variables according to the output you mentioned:
cout << "your string has " << total << " total characters, " << letters << " letters, " << numbers << " numerical characters, and " << otherCharacters << " characters.";

C++ show vowel and consonant and count it

When user input number from 1 - 26 (which mean a to z), how to show the the letter and count how many vowel and consonant inside it.
Example:
Users input=13
Then will show =
a
b
c
d
e
f
g
h
i
j
k
l
m
Vowel = 3
Consonant = 10
i just now how to count it not to show it
#include <iostream>
using namespace std;
int main (){
int vow=0, con=0;
char let;
.........
.........
if (let=='a' || let=='e' || let=='i' || let=='o' || let=='u'){vow++}
else{con++}
cout<<"Vowel = "<<vow<<endl;
cout<<"Consonant"<<con<<endl;
}
Your if statement does not do what you expect it to. The correct syntax for this is
if (let=='a' || let=='e' || let=='i' || let=='o' || let=='u')
The reason the current versions is incorrect is because it is equivalent to
if ((let=='a') or ('e') or ('i') or ('o') or ('u'))
So 'e', 'i', etc are being evaluated for truthiness and ord to the first condition. Only an empty string in this case will evaluate to false, all of these characters will be true. So your statement evaluates to
if ((let=='a') or true or true or true or true)
Which will always be true.
#include <iostream>
using namespace std;
/**
* Checks if the given letter is a vowel.
*/
bool isVowel(char let) {
return let == 'a' || let == 'e' || let == 'i' || let == 'o' || let == 'u';
}
/**
* Returns the character for the given int.
*/
char toChar(int num) {
return (char) ('a' + num - 1);
}
int main (void) {
int vow = 0,
con = 0,
num,
i;
char let;
cout << "Please enter a number: ";
cin >> num;
for (i = 1; i <= num; ++i) {
let = toChar(i);
if (isVowel(let)) vow++;
else con++;
}
cout << "The letter was \"" << let
<< "\" and there were " << vow
<< " vowels and " << con
<< " consonants." << endl;
return 0;
}
To show the letters, you can use a for loop, using a char as index.
int n = 13;
unsigned int vowel = 0;
unsigned int consonant = 0;
int a = (int)'a';
for (char letter = 'a'; (int)letter < a + n; letter++) {
cout << letter << " ";
if (is_vowel(letter)) vowel++;
else consonant++;
}
cout << std::endl << "vowels: "<< vowel << " consonants: " << consonant << std::endl;
So, you must implement the is_vowel method.

Not getting out of the loop

I am using this program to implement Mono alphabetic cipher. The problem i am getting is when i input plain text it doesn't get out of the loop when condition is met which is pressing the enter key.Here is my code.
int main()
{
system("cls");
cout << "Enter the plain text you want to encrypt";
k = 0;
while(1)
{
ch = getche();
if(ch == '\n')
{
break; // here is the problem program not getting out of the loop
}
for(i = 0; i < 26; i++)
{
if(arr[i] == ch)
{
ch = key[i];
}
}
string[k] = ch;
k++;
}
for(i = 0;i < k; i++)
{
cout << string[i];
}
getch();
return 0;
}
Here the problem is probably the fact that getche() (unlike getchar()) just returns the first character when there are more then one inputed and you are on windows (othewise you wouldn't use cls) then the EOL is encoded with \r\n.
What happens is that getche() returns \r so your break is never actually executed. You should change it to getchar() even because getche is a non standard function.
You can even try to look for \r instead that \n in your situation but I guess the \n would remain in the buffer causing problems if you need to fetch any additional input later (not sure about it).
Relying on old C libraries in C++ is yucky. Consider this alternative:
#include <iostream>
#include <string>
using namespace std; // haters gonna hate
char transform(char c) // replace with whatever you have
{
if (c >= 'a' && c <= 'z') return ((c - 'a') + 13) % 26 + 'a';
else if (c >= 'A' && c <= 'Z') return ((c - 'A') + 13) % 26 + 'A';
else return c;
}
int main()
{
// system("cls"); // ideone doesn't like cls because it isnt windows
string outstring = "";
char ch;
cout << "Enter the plain text you want to encrypt: ";
while(1)
{
cin >> noskipws >> ch;
if(ch == '\n' || !cin) break;
cout << (int) ch << " ";
outstring.append(1, transform(ch));
}
cout << outstring << endl;
cin >> ch;
return 0;
}
I would do something like the fallowing which uses standard C++ I/O.
#include <iostream>
#include <string>
using namespace std;
// you will need to fill out this table.
char arr[] = {'Z', 'Y', 'X'};
char key[] = {'A', 'B', 'C'};
int main(int argc, _TCHAR* argv[])
{
string sInput;
char sOutput[128];
int k;
cout << "\n\nEnter the plain text you want to encrypt\n";
cin >> sInput;
for (k = 0; k < sInput.length(); k++) {
char ch = sInput[k];
for(int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
{
if(arr[i] == ch)
{
ch = key[i];
break;
}
}
sOutput[k] = ch;
}
sOutput[k] = 0;
cout << sOutput;
cout << "\n\nPause. Enter junk and press Enter to complete.\n";
cin >> sOutput[0];
return 0;
}