C++ character counter - c++

I need to design a character counter, whenever I enter single char. it gives me the next one in succession e.g. enter A, it shows B, Z-->A for both lower and Upper letters. only using (for loop)
What went wrong?
The characters doesn't show in order I mean whenever I enter a letter it's random response giving me a random number that hasn't any function of the program the body looks acceptable but in turns of internal details something isn't going the way I wanted to be. Here's my code:
char count[256];
int size = 0;
for ( c != 0; ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) ; c++ )
{
size += count[c];
}
return size;
return 0;

using ASCI codes will be helpfull here
for e.g
char alphabet ;
cout <<"Enter alphabet"<<endl;
cin>>alphabet ;
int a = (int) alphabet;
a++;
cout<<"Next alphabet is :"<<(char)a<<endl ;

Take your input
Check if it is an alphabet
Check if it is a 'z' or 'Z', if so, make it an 'a', or 'A' (hint: use ascii codes and a little arithmetic)
Else add a character to it
Print

Related

Use ASCII code to encrypt a message

The question requires to output the input following the rules below:
1. if the input character is between A-Z, or a-z, the out put character would be
the following letter, abc-->bcd
2. if the input is Z or z, the output would be A or a, z->a,Z->A
3. if the input is space, then it remains the same
4. if the input is anything else, increment its ascii value by 1, and print.
This is an example:
input: abcZ ]
output: bcdA ^
Here is my code:
#include <iostream>
using namespace std;
int main()
{//use ASCII to get a code for input by changing a to b, b to c....z to a, space remain the same, everything else ++
char c,d;
int i=0;
for(i=0;;i++)
{
if (('A' <= (c=cin.get()) < 'Z')||('a' <= (c=cin.get()) < 'z'))
{
d=c+1;
}
else if(c=cin.get()==32)// ascii value of space is 32
d=c;
else if((c=cin.get())=='Z')
d='A';
else if((c=cin.get())=='z')
d='a';
else
{
c++;
d=c;
}
cout<<d;
}
cout<<endl;
return 0;
}
This is the output:
What I am thinking is that ♂ is the output of enter key, but I dont want an output for enter key.
space,Z and z don't convert properly either.
Can anyone help me with the code?Thank you.
You've got a bunch of problems here. Here are some hints:
1) Call cin.get() just once per loop iteration. That is:
for (...)
{
c = cin.get();
// do not call cin.get() beyond this point.
// use the c variable instead
...
}
2) Be careful around your compound conditionals.
Instead of: ('A' <= c < 'Z'), you really want: ('A' <= c && c < 'Z')
3) Add another condition to check for 10. This is the code for the line feed character. If this is detected, just do a cout << endl
There are a number of ways to simplify the logic here too. Keep trying!

C++ caesar cipher — understanding ascii keys

I am currently doing a caesar cipher program. It should encrypt for both lower and upper case.
e.g
If I typed in a, it will then shift the keys by 3 and the final output will become d.
Take a look at my codes
char c;
c = (((97-52)+3) % 26) + 52;
cout << c;
The letter 'a' has an ASCII code of 97.
So by right
1) ((97-52)+3) will give you 48
2) 48 % 26 will give you 8 since 48/26 will give you a remainder of 8.
3) 8 + 52 = 60(which will by right give you a value of '>' according to the ascii table)
but my output that I have got is J and I don't understand which am I getting the output of 'J' instead of '>'
My concepts might be wrong so I need help.
Let me link ASCII chart I use first: http://pl.wikipedia.org/wiki/ASCII
The website is polish, but table itself is in english.
I think it's plainly obvious that problem is the equatation you use:
(((letter-52)+3) % 26) + 52;
Actually first letter in ASCII is 65(hexadecimal 0x41 - follow with the chart provided).
Your idea with the modulo would be fine, if there were no chars between letter blocks in ASCII. But there are (again check up chart).
That is why you should manually check if the sign:
is a capital letter: if (letter >= 0x41 && letter <= 0x5a)
is a non-capital: if (letter >= 0x61 && letter <= 0x7a)
Usually when making Ceasar cipher, you should follow these:
Replace a capital letter with capital letter moved in the alphabet by a given number.
If the letter would be out of alphabet scope, continue iteration from the start of alphabet (X moved 5 to the right would give C).
Other chars stay the same
Now let's implement this (in code I'll use letter values of chars - to avoid mistakes):
#include <iostream>
#include <cstdlib>
using namespace std;
string Ceasar(string input, int offset)
{
string result = "";
for (int i = 0; i < input.length(); ++i)
{
// For capital letters
if (input[i] >= 'A' && input[i] <= 'Z')
{
result += (char) (input[i] - 'A' + offset) % ('Z' - 'A') + 'A';
continue;
}
// For non-capital
if (input[i] >= 'a' && input[i] <= 'z')
{
result += (char) (input[i] - 'a' + offset) % ('z' - 'a') + 'a';
continue;
}
// For others
result += input[i];
}
return result;
}
int main()
{
cout << Ceasar(string("This is EXamPLE teXt!?"), 8).c_str();
system("PAUSE");
}

C++ manipulating numbers in ASCII to stay only in range of letters

#include <iostream>
using namespace std;
Int main() {
cout<<"Give me a letter" <<endl;
char letter;
cin>>letter;
cout<<letter;
(Int)letter;
letter+=2;
cout<<(char)letter;
(Int)letter;
letter-=25;
cout<<(char)letter;
return 0;
}
How would I manipulate the numbers in a way so that the numbers will always output a letter.
ie: if the letter z was chosen and adding 2 is a symbol how would I manipulate it in a way so that it will always stay between the numbers for capital numbers and uncapitalized numbers. Thanks. Please try to keep answers at a beginner level please I am new to this.
if(letter > 'z') {
//do stuff
}
if(letter < 'a' && letter > 'Z') {
//do stuff
}
if(letter < 'A') {
//do stuff
}
It just depends on how you want to handle the character when it goes into one of the three ranges on the ASCII chart in which the characters are not letters.
As a side note, you don't have to cast a char to an int to do math with it.
char myChar = 'a' + 2;
cout << myChar;
This will print: c
c has an ASCII value of 2 more than a.
The surest method is to use a table for each category, and do
your arithmetic on its index, modulo the size of the table.
Thus, for just lower case letters, you might do something like:
char
transcode( char original )
{
char results = original;
static std::string const lower( "abcdefghijklmnopqrstuvwxyz" );
auto pos = std::find( lower.begin(), lower.end(), results );
if ( pos != lower.end() ) {
int index = pos - lower.begin();
index = (index + 2) % lower.size();
results = lower[ index ];
}
return results;
}
This solution is general, and will work regardless of the sets
of letters you want to deal with. For digits (and for upper and
lower case, if you aren't too worried about portability), you
can take advantage of the fact that the code points are
contiguous, and do something like:
char
transcode( char original )
{
char results = original;
if ( results >= '0' && results <= '9' ) {
char tmp = results - '0'
tmp = (tmp + 2) % 10;
results = tmp + '0';
}
return results;
}
An alternative implementation would be to use something like:
results = results + 2;
if ( results > '9' ) {
results -= 10;
}
in the if above. These two solutions are mathematically
equivalent.
This is only guaranteed to work for digits, but will generally
work for upper or lower case if you limit yourself to the
original ASCII character set. (Be aware that most systems today
support extended character sets.)
You can test directly against ASCII chars by using 'x' notation. Further, you can test things together using && ("and" respectively"):
if ('a' <= letter && letter <= 'z') {
// Letter is between 'a' and 'z'
} else if ('A' <= letter && letter <= 'Z')) {
// Letter is between 'A' and 'Z'
} else {
// Error! Letter is not between 'a' and 'z' or 'A' and 'Z'
}
Or you can use the standard library function std::isalpha which handles this for you:
if (std::isalpha(letter)) {
// Letter is between 'a' and 'z' or 'A' and 'Z'
} else {
// Error! Letter is not between 'a' and 'z' or 'A' and 'Z'
}

Need assistance understanding a shift calculation and trimming some fat off my code

I was going over this code to read a file on my desktop that decrypts a cesar cipher code and I am stuck trying to figure out how the shift is calculated in this program.
From what I can tell, Max e's is the shifted letter with the highest frequency. Since e's are the most common letter in English, the program is trying to set the highest frequency char in the cipher, to an 'e' in English. Which is good, as far as it goes, but there are many phrases where e's are NOT the most frequent letter, and then it will fall on it's face.
So, how can I tell the program to guess at the most frequent cipher letter to be an e in plain text BUT in case it isn't, then proceed to try an e shifted to the second most frequent letter in the text, and so on, until I find it?
A friend helped with that part but has poor English so it is difficult for him to explain it to me. Can someone please elaborate? Assistance is greatly appreciated! Let me know what you think:
#include <iostream>
#include <string>
#include <cctype> // isalpha, islower, isupper, functions
#include <fstream>
using namespace std;
string caesarShift(string text, int shift);
int main()
{
int maxEs = 0; // # of e's in maxString
int currentEs = 0; // # of e'sin currentString
string maxString; // decrypted caesar shift with most e's
string currentString; //decrypted caesar shift
string cipher; // Stores cipher text
char ch; // Stores currentcharacter for reading
ifstream fin("/Users/jasonrodriguez/Desktop/encrypted.txt"); //opens "encrypted.txt" file
while( fin.get(ch) ) // readseach char into the cipher till EOF
{
cipher += ch;
}
fin.close(); // be safe andclose file
for(int i=0; i < 26; i++)
{
currentEs =0; // Reset counter
currentString =caesarShift(cipher, i); // get shifted text
for(unsigned int x=0; x <currentString.size(); x++) // check each character of stringarray
{
if(currentString[x] == 'e' || currentString[x] == 'E') // check fore's
{
currentEs++; // increment Ecounter
}
}
if(currentEs > maxEs) //if currentEs is greater than maxEs, replace max with current
{
maxEs =currentEs;
maxString= currentString;
}
}
cout << maxString << endl;
return 0;
}
/**
string caesarShift(string text, int shift)
Decrypts Caesar Shift using text and shift
*/
string caesarShift(string text, int shift)
{
shift = shift % 26; // Morethan 26 is redundant and unneeded
char ch = 0; // holds current character
char chs = 0; // holds shiftedcharacter
for(unsigned int i=0; i < text.size();i++)
{
ch = text[i];
if( isalpha(ch) )
{
chs = ch -shift; // reverse shifting
if( (islower(ch) && chs < 'a' ) // If is lowercase andshifted value is lower than 'a'
||
( isupper(ch) && chs < 'A' ) ) // Ifis uppercase and shifted value is lower than 'A'
{
chs += 26; // Add 26(number ofletters) to get back to the correct place in alphabet
}
text[i] =chs; // Set character to shifted character
}
}
return text;
}
Questions:
From what I can tell, Max e's is the shifted letter with the highest frequency. Since e's are the most common letter in English, the program is trying to set the highest frequency char in the cipher, to an 'e' in English. Which is good, as far as it goes, but there are many phrases where e's are NOT the most frequent letter, and then it will fall on it's face. So, how can I tell the program to guess at the most frequent cipher letter to be an e in plain text BUT in case it isn't, then proceed to try an e shifted to the second most frequent letter in the text, and so on, until I find it?
I think if I shift a character by a shift amount the character may or may not be out of bounds. 'a' + 3 is 'd' ok, 'x' + 3 is '{' not ok. So if the character is over 'z' take away 26, if under 'a' add 26. can be a usable function. However, can you please explain to me how the shift is calculated in the program and is applied it to the file? It has me totally stumped :(
Calculating a shift:
First, you need to mapy the letters 'A' through 'Z' (assuming only uppercase letters) to the integers 0 through 25. C++ let's you do this easily with subtraction:
n = c - 'A';
Now you can perform the shift with modulus arithmetic:
n = (n + shift) % 26;
Finally map back to a letter:
p = n + 'A';
(Note that you will need apprporiate declarations for the variables used in these examples. I suggest that you use more meaningful names than the single-letter variables names I use.)

How does this array conversion work ( lowercase to uppercase using a string)?

I got the program to work as expected, but can anyone explain how it works?
#include <iostream>
using namespace std;
int main(void) {
int exit;
string name;
cin >> name;
for (int i = 0; i < name.length(); i++) {
// the line below is the one I don't understand
if ('a' <= name[i] && name[i] <= 'z') name[i] = char(((int)name[i]) - 32);
}
cout << name;
cin >> exit;
return 0;
}
EDIT: Let me rephrase:
The thing I don't understand is how does the string-to-array deal work, as in:
'a'<= name[i]. What exactly does this compare and how?
EDIT2
Thanks for the quick responses guys, love you all. I figured it out.
This is the line:
if('a'<=name[i] && name[i]<='z')name[i]=char(((int)name[i])-32);
broken down:
if( 'a'<=name[i] ) {
if( name[i]<='z' ) {
// name_int is a temporary, which the above code implicitly creates,
// but doesn't give a name to:
int name_int = name[i];
name_int = name_int - 32;
name[i] = char(name_int);
}
}
and note that 32 happens to equal 'a'-'A' in the character encoding you are using.
(Technically name_int should be an int&& or somesuch, but no need to be that confusing.)
I assume from the edit in your comment that you are wondering how the [] can apply to a string object. The operator [] is overloaded for string to return a reference to the character at the specified position offset of the represented string. There need not be any direct conversion of the string into an array. The code that implements the overload could well be walking a linked list. It depends on how string was implemented.
It assumes ASCII character format where to convert from lowercase to uppercase you subtract 32 from the original ASCII value. This is because the ASCII values for uppercase are smaller than those for lower case and it's a constant difference between A and a, B and b and so on.
For reference: http://www.asciitable.com/
'a' <= name[i] && name[i] <= 'z'
This line is comparing the corresponding ASCII values of these two characters. 'a' in ASCII is 97 and 'z' is 122. If name[i] is one of the characters from 'a' to 'z' the expression returns true. This is commonly used to check if a variable is alphabetic.
if ('a' <= name[i] && name[i] <= 'z')
char objects are numeric values similar to ints. So 'a' <= name[i] is simply testing if the numeric value of 'a' is less than or equal to the character you're examining. Combined with name[i] <= 'z' and you're testing if the numeric value of name[i] is between the values of 'a' and 'z'. Now, it just so happens that the most common scheme for assigning numeric values to chars, named "The American Standard Code for Information Interchange" (ASCII), has the alphabet arranged in order; 'a' + 1 = 'b', 'b' + 1 = 'c', and so on. So figuring out if the character is between 'a' and 'z' tells you if it's a lower case letter.
name[i] = char(((int)name[i]) - 32);
Once you know that chars are just numeric values you might infer from the basic properties of arithmetic which we all learned in grade school that 'a' + ('A' - 'a') results in the value 'A'. Further, ASCII has the upper case alphabet arranged similarly to the lower case alphabet so that 'A' + 1 = 'B', etc. So taking anycharin the lower case alphabet and adding'A' - 'a'will result in the upper case version of that letter. In ASCII'A' - 'a'` happens to have the value -32. So take the numeric value for a lower case letter, subtract 32, and you have the value for the upper case letter.
For comparison here's a version of the code that doesn't depend on ASCII:
auto l = std::locale();
if (std::islower(name[i], l))
name[i] = std::tolower(name[i], l);