I have finished my program about encryption. The problem is, I need a shortcut. The program I have coded is too long and not very suitable. I'm just new to c++ programming. Can someone help me out? thanks! :) Here's my program:
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main()
{
c:char crypt[25], cons;
int ctr;
cout<<"Input your 26-character cipherstring below.\n\n";
cout<<"ABCDEFGHIJKLMNOPQRSTUVWXYZ\n";cin>>crypt;
e:char string[65535];
cout<<"\nInput your string (input your spaces as any non-alphabet character).\n";cin>>string;
cout<<"\n\nEncrypted string: "; //std::string
for(ctr=0;ctr<=strlen(string);ctr++)
{
switch(string[ctr])
{
case('a'): cout<<crypt[0]; break;
case('b'): cout<<crypt[1]; break;
case('c'): cout<<crypt[2]; break;
case('d'): cout<<crypt[3]; break;
case('e'): cout<<crypt[4]; break;
case('f'): cout<<crypt[5]; break;
case('g'): cout<<crypt[6]; break;
case('h'): cout<<crypt[7]; break;
case('i'): cout<<crypt[8]; break;
case('j'): cout<<crypt[9]; break;
case('k'): cout<<crypt[10]; break;
case('l'): cout<<crypt[11]; break;
case('m'): cout<<crypt[12]; break;
case('n'): cout<<crypt[13]; break;
case('o'): cout<<crypt[14]; break;
case('p'): cout<<crypt[15]; break;
case('q'): cout<<crypt[16]; break;
case('r'): cout<<crypt[17]; break;
case('s'): cout<<crypt[18]; break;
case('t'): cout<<crypt[19]; break;
case('u'): cout<<crypt[20]; break;
case('v'): cout<<crypt[21]; break;
case('w'): cout<<crypt[22]; break;
case('x'): cout<<crypt[23]; break;
case('y'): cout<<crypt[24]; break;
case('z'): cout<<crypt[25]; break;
case('A'): cout<<crypt[0]; break;
case('B'): cout<<crypt[1]; break;
case('C'): cout<<crypt[2]; break;
case('D'): cout<<crypt[3]; break;
case('E'): cout<<crypt[4]; break;
case('F'): cout<<crypt[5]; break;
case('G'): cout<<crypt[6]; break;
case('H'): cout<<crypt[7]; break;
case('I'): cout<<crypt[8]; break;
case('J'): cout<<crypt[9]; break;
case('K'): cout<<crypt[10]; break;
case('L'): cout<<crypt[11]; break;
case('M'): cout<<crypt[12]; break;
case('N'): cout<<crypt[13]; break;
case('O'): cout<<crypt[14]; break;
case('P'): cout<<crypt[15]; break;
case('Q'): cout<<crypt[16]; break;
case('R'): cout<<crypt[17]; break;
case('S'): cout<<crypt[18]; break;
case('T'): cout<<crypt[19]; break;
case('U'): cout<<crypt[20]; break;
case('V'): cout<<crypt[21]; break;
case('W'): cout<<crypt[22]; break;
case('X'): cout<<crypt[23]; break;
case('Y'): cout<<crypt[24]; break;
case('Z'): cout<<crypt[25]; break;
default: cout<<" "; break;
}
}
cout<<"\n\n";
/*cout<<"Input 'c' to re-input your cipherstring.\n 'e' to reuse your cipherstring.\n 'q' to quit. ";
comm:cout<<"\nCommand: "; cin>>cons;
switch (cons)
{
case('c'): cout<<endl; goto c; break;
case('C'): goto c; break;
case('e'): goto e; break;
case('E'): goto e; break;
case('q'): break;
case('Q'): break;
default: cout<<"Invalid command. Please refer to the command list above.\n";goto comm;
}*/
system("PAUSE"); return 0;
}
You can replace that huge switch statement with this:
if (isalpha(string[ctr]))
{
int index = toupper(string[ctr]) - 'A';
cout << crypt[index];
}
else
cout << " ";
Also, do not call strlen for every iteration of the for loop, just do it once:
for(int ctr=0, len=strlen(string); ctr<len; ctr++)
{
....
}
A few other things of note:
crypt is too small, it should have size 27
If you use getline instead of operator>>, you can have the user enter spaces properly
Your code is prone to buffer overflows. Use std::string and you can pretty much forget about those.
Note, that as Kerrek says, this assumes that in the character set you are using, the uppercase letters A-Z are in sequence. But I think that the cases where this is not true are so exceedingly rare, that you can safely ignore them.
Related
void getDay() {
bool repeat;
do
{
cout << "Enter the day code (first 2 letters): ";
cin >> weekDay1;
cin >> weekDay2;
weekDay1 = toupper(weekDay1);
weekDay2 = toupper(weekDay2);
switch (weekDay1)
{
case 'M':
break;
case 'T':
break;
case 'W':
break;
case 'F':
break;
case 'S':
break;
default:
cout << "Invalid input. Please try again.\n";
repeat = true;
break;
}
switch (weekDay2)
{
case 'O':
break;
case 'U':
break;
case 'E':
break;
case 'H':
break;
case 'R':
break;
case 'A':
break;
default:
cout << "Invalid input. Please try again.\n";
repeat = true;
break;
}
}while (repeat == true);
return;
}
I need this function to run once, and loop if the input is not one of the accepted characters. I'm trying to prevent any bad input, but it loops infinitely if the input entered on the initial run is not accepted. It works fine if the input is good on the first run, but I keep getting run-time errors for not initializing bools and I need some help adjusting this control.
The condition in the while loop is always true because you never set it to false in its body. You can do something like this:
void getDay() {
// Initializing while declaring is a good practice.
bool repeat = false;
do {
.
.
repeat = false;
.
switch(...) {
...
}
} while (repeat);
}
Now, repeat = true is only called if one of the switch statements invokes default.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have made a simple encryption function,which encrypts everything except 0-9 numbers (ignoring the special characters).
Here is the code.
#include <iostream>
using namespace std;
void encrypt(char s[])
{
char *ptr;
ptr=s;
while(*ptr)
{
switch (*ptr)
{
case 'a': *ptr='b';
break;
case 'b': *ptr='a';
break;
case 'c': *ptr='z';
break;
case 'd': *ptr='y';
break;
case 'e': *ptr='c';
break;
case 'f': *ptr='d';
break;
case 'g': *ptr='x';
break;
case 'h': *ptr='g';
break;
case 'i': *ptr='i';
break;
case 'j': *ptr='h';
break;
case 'k': *ptr='f';
break;
case 'l': *ptr='j';
break;
case 'm': *ptr='q';
break;
case 'n': *ptr='o';
break;
case 'o': *ptr='p';
break;
case 'p': *ptr='m';
break;
case 'q': *ptr='n';
break;
case 'r': *ptr='l';
break;
case 's': *ptr='k';
break;
case 't': *ptr='x';
break;
case 'u': *ptr='w';
break;
case 'v': *ptr='u';
break;
case 'w': *ptr='v';
break;
case 'x': *ptr='t';
break;
case 'y': *ptr='s';
break;
case 'z': *ptr='r';
break;
case 1: *ptr=5;
break;
case 2: *ptr=6;
break;
case 3: *ptr=0;
break;
case 4: *ptr=1;
break;
case 5: *ptr=2;
break;
case 6: *ptr=7;
break;
case 7: *ptr=4;
break;
case 8: *ptr=3;
break;
case 9: *ptr=8;
break;
case 0: *ptr=9;
break;
default: *ptr=*ptr;
break;
}
*ptr++;
}
*ptr='\0';
}
int main()
{
char password[10];
cout<<"Enter the password\n";
cin>>password;
encrypt(password);
cout<<password<<endl;
return 0;
}
Here is a sample output
sh-4.3$ main
Enter the password
thisisanex!!1234567
xgikikboct!!1234567
You need to use the character '1' not the integer value 1.
So use case '1': instead of case 1: and so on for the other numbers.
As nos said, the character is different from the integer value.
However, looking at your code, it would make a lot more sense to do this:
#include <iostream>
#include <string>
using namespace std;
int main(){
string charset = "abcdefghijklmnopqrstuvwxyz1234567890";
string scrambledcharset = "r5b6ng1fcl8htau9i74kxy0vjw3psemqz2do"; //Whatever order you want
string uIn;
string output;
cout << "Enter your string: ";
cin >> uIn;
cin.ignore();
for(int i = 0; i < uIn.length(); i++){
for(int j = 0; j < charset.length(); j++){
if(uIn[i] == charset[j]){
output += scrambledcharset[j];
}
}
}
cout << "\nScrambled: " << output;
return 0;
}
I'm having trouble understanding my C++ switch statement.
I have to enter the accepted integer interval twice for the function to return to the switch. And then it falls straight through to case 2.
Inherited Class:
class Fugl : public DyrLuft
{
private:
int alder;
public:
Fugl() : DyrLuft()
{ }
void les()
{
do
{
cout << "\nSkriv inn fuglens alder: ";
cin >> alder;
if(alder < 0 || alder > 130)
cout << "\nDenne alderen virket usannsynlig, prøv igjen!\n";
} while(alder < 0 || alder > 130);
}
};
Main:
int main()
{
char valg = '\q';
cout << "Hvilken dyreart ønsker du å registrere? (Q for å avslutte)"
<< "\n1) - Fugl \n2) - Fisk \n3) - Insekt \n4) - Skalldyr\n";
do
{
cin >> valg;
switch(valg)
{
case '1':
{
Fugl fugl; fugl.les();
} break;
case '2':
{
Fisk fisk; fisk.les();
} break;
case '3':
{
Insekt insekt; insekt.les();
} break;
case '4':
{
Skalldyr skalldyr; skalldyr.les();
} break;
case 'Q': return 0;
case 'q': return 0;
default: cout << "Velg en av ovennevnte!\n";
}
} while(valg != 'Q' || valg != 'q');
return 0;
}
I dont know what is happening in your case, but I ran your code and it works just fine for me. Entered 1,4,Q and program exited as expected....Could be a compiler or a DyrLuft class issue(i just removed the inheritance to make it work, also lines from case 2,3,4).
You have:
case '1':
{
Fugl fugl; fugl.les();
} break;
When you run this you create a Fug1 object and then you call the les() function. When you enter an appropriate age in les() the function returns. Since the break; is outside of the case block it is actually breaking the switch statement and going to the end of the loop. Then it cycles back to the top of the loop and makes you enter a selection again. If you move break inside og the case block it functions as it should. This is the changed loop:
do
{
cout << "Hvilken dyreart ønsker du å registrere? (Q for å avslutte)"
<< "\n1) - Fugl \n2) - Fisk \n3) - Insekt \n4) - Skalldyr\n";
cin >> valg;
switch (valg)
{
case '1':
{
Fugl fugl; fugl.les();
break;
}
case '2':
{
Fisk fisk; fisk.les();
break;
}
case '3':
{
Insekt insekt; insekt.les();
break;
}
case '4':
{
Skalldyr skalldyr; skalldyr.les();
break;
}
case 'Q': return 0;
case 'q': return 0;
default: cout << "Velg en av ovennevnte!\n";
}
} while (valg != 'Q' || valg != 'q');
I have made a program in c++ for encoding and decoding morse code.
My program is working and the decoded message is fine but without spaces is there any way to add space.
#include <iostream>
#include <string>
using namespace std;
string translateMorseCode(string sentence);
string decoceMorseCode (string sentence);
int main()
{
string sentence;
cout<<"Enter word or sentence: ";
getline(cin,sentence);
cout<<"\nMorse Code is:\n";
//convert input message into morse
cout<<translateMorseCode(sentence)<<endl;
//copying morse code into decode string for decoding
string decode = translateMorseCode(sentence);
cout<<"\nDecoding morse code is text"<<endl;
//converting back ito text string
cout<<decoceMorseCode (decode);
return 0;
}
string decoceMorseCode (string sentence)
{
string delimiter = " ";
string decode ="";
int pos = 0;
string token;
while ((pos = sentence.find(delimiter)) != string::npos) {
token = sentence.substr(0, pos);
if(token==".-")
{
decode.append("a");
}
else if(token=="-...")
{
decode.append("b");
}
else if(token=="-.-.")
{
decode.append("c");
}
else if(token=="-..")
{
decode.append("d");
}
else if(token==".")
{
decode.append("e");
}
else if(token=="..-.")
{
decode.append("f");
}
else if(token=="--.")
{
decode.append("g");
}
else if(token=="....")
{
decode.append("h");
}
else if(token=="..")
{
decode.append("i");
}
else if(token==".---")
{
decode.append("j");
}
else if(token=="-.-")
{
decode.append("k");
}
else if(token==".-..")
{
decode.append("l");
}
else if(token=="--")
{
decode.append("m");
}
else if(token=="-.")
{
decode.append("n");
}
else if(token=="---")
{
decode.append("o");
}
else if(token==".--.")
{
decode.append("p");
}
else if(token=="--.-")
{
decode.append("q");
}
else if(token==".-.")
{
decode.append("r");
}
else if(token=="...")
{
decode.append("s");
}
else if(token=="-")
{
decode.append("t");
}
else if(token=="..-")
{
decode.append("u");
}
else if(token=="...-")
{
decode.append("v");
}
else if(token==".--")
{
decode.append("w");
}
else if(token=="-..-")
{
decode.append("x");
}
else if(token=="-.--")
{
decode.append("y");
}
else if(token=="--..")
{
decode.append("z");
}
else if(token=="-----")
{
decode.append("0");
}
else if(token==".----")
{
decode.append("1");
}
else if(token=="..---")
{
decode.append("2");
}
else if(token=="...--")
{
decode.append("3");
}
else if(token=="....-")
{
decode.append("4");
}
else if(token==".....")
{
decode.append("5");
}
else if(token=="-....")
{
decode.append("6");
}
else if(token=="--...")
{
decode.append("7");
}
else if(token=="---..")
{
decode.append("8");
}
else if(token=="----.")
{
decode.append("9");
}
sentence.erase(0,pos + delimiter.length());
}
return decode ; // returnung decoded text
}
//function convert input message into morse return Morse Code as String
string translateMorseCode(string sentence)
{
string MorseCode="";
for(int i=0;i<sentence.length();i++){
switch (sentence[i]){
case 'a':
case 'A':
MorseCode.append(".- ");
break;
case 'b':
case 'B':
MorseCode.append("-... ");
break;
case 'c':
case 'C':
MorseCode.append("-.-. ");
break;
case 'd':
case 'D':
MorseCode.append("-.. ");
break;
case 'e':
case 'E':
MorseCode.append(". ");
break;
case 'f':
case 'F':
MorseCode.append("..-. ");
break;
case 'g':
case 'G':
MorseCode.append("--. ");
break;
case 'h':
case 'H':
MorseCode.append(".... ");
break;
case 'i':
case 'I':
MorseCode.append(".. ");
break;
case 'j':
case 'J':
MorseCode.append(".--- ");
break;
case 'k':
case 'K':
MorseCode.append("-.- ");
break;
case 'l':
case 'L':
MorseCode.append(".-.. ");
break;
case 'm':
case 'M':
MorseCode.append("-- ");
break;
case 'n':
case 'N':
MorseCode.append("-. ");
break;
case 'o':
case 'O':
MorseCode.append("--- ");
break;
case 'p':
case 'P':
MorseCode.append(".--. ");
break;
case 'q':
case 'Q':
MorseCode.append("--.- ");
break;
case 'r':
case 'R':
MorseCode.append(".-. ");
break;
case 's':
case 'S':
MorseCode.append("... ");
break;
case 't':
case 'T':
MorseCode.append("- ");
break;
case 'u':
case 'U':
MorseCode.append("..- ");
break;
case 'v':
case 'V':
MorseCode.append("...- ");
break;
case 'w':
case 'W':
MorseCode.append(".-- ");
break;
case 'x':
case 'X':
MorseCode.append(".-- ");
break;
case 'y':
case 'Y':
MorseCode.append("-.-- ");
break;
case 'z':
case 'Z':
MorseCode.append("--.. ");
break;
case ' ':
MorseCode.append(" ");
break;
case '1':
MorseCode.append(".---- ");
break;
case '2':
MorseCode.append("..--- ");
break;
case '3':
MorseCode.append("...-- ");
break;
case '4':
MorseCode.append("....- ");
break;
case '5':
MorseCode.append("..... ");
break;
case '6':
MorseCode.append("-.... ");
break;
case '7':
MorseCode.append("--... ");
break;
case '8':
MorseCode.append("---.. ");
break;
case '9':
MorseCode.append("----. ");
break;
case '0':
MorseCode.append("----- ");
break;
}
}
return MorseCode;// return Morse Code
}
The problem is that you use a double space in your morse output to encode a word boundary, but your decoder skips all spaces. It therefore skips double spaces too, which is why it doesn't know where to put a space in the decoded output.
According to wiki:
Each character (letter or numeral) is represented by a unique sequence of dots
and dashes. The duration of a dash is three times the duration of a dot. Each
dot or dash is followed by a short silence, equal to the dot duration. The
letters of a word are separated by a space equal to three dots (one dash), and
the words are separated by a space equal to seven dots. The dot duration is the
basic unit of time measurement in code transmission.[1] To increase the speed of
the communication, the characters are encoded so the length of each character in
Morse is approximately inversely proportional to its frequency of occurrence in
English. Thus, the most common letter in English, the letter "E," has the
shortest code, a single dot.
So in my opinion:
Two "\s" should be between words.
One "\s" between single char.
#Neska gave you the basic answer but did not explain where the space gets interpreted.
When you get the tag decoded your logic should be able to detect the silence between the dots and dashes. Otherwise, it would not be able to determine where an individual character ends and the next character begins. That logic should detect the longer (seven dots long) interval between the end of a word and the beginning of the next work. Put in a special character (not a . or a dash) to be interpreted as a space in your morse code interpreter.
If you are interpreting text input and searching for the next delimiter (such as a space) in order to translate the dots and dashes, output the delimiters as well. That will put in the appropriate number of spaces
For example
.-^-^^-...^-.--
translates to
at^by
where the ^ character shows where the space should be.
Your code translates this as atby
I have found a solution by myself and it was quite simple - I just added
else if (" ")
{
decode.append(" ");
}
before the
sentence.erase(0,pos + delimiter.length());
I am using Windows 7 Ultimate. I am new to C++. Following is my exercise for switch statement.
void GradeBook::inputGrades()
{
int grade;
cout << "Enter Grade: " << endl;
while((grade=cin.get()) != EOF)
{
switch(grade)
{
case 'A':
case 'a':
aCount++;
break;
case 'B':
case 'b':
bCount++;
break;
case 'C':
case'c':
cCount++;
break;
case 'd':
case 'D':
dCount++;
break;
case 'F':
case 'f':
fCount++;
break;
case '\n':
case ' ':
case '\t':
break;
default:
cout << "Incorrect data. Re Enter" << endl;
break;
}
}
}
I run this inside netbeans, and I pressed all the combinations ctrl+c , ctrl+z, ctrl+d but it is not ending!! Why is that? Have I done something wrong? Please help!!
An EOF character is Ctrl+Z followed by a newline character on Windows platforms.
Presumably that will be the same for the console within Netbeans.
cin.get() is pretty low level. The code should use a higher-level interface. It's supposed to read a character at a time, so write it that way:
char grade;
while (cin >> grade)
The stream extractor will fail at end of file, and that will make the while loop terminate.