This is a somewhat slow solution because you end up with an expensive search, but it does what you want. The alphabet string holds all of your valid characters and the values array has the corresponding value at each index. Once you have the index for alphabet, you can get the value from values:
#include <iomanip>
#include <iostream>
int main()
{
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
int values[] = {
25,24,23,22,21,20,19,18,
17,16,15,14,13,12,11,10,
9,8,7,6,5,4,3,2,1,0
};
char word[10];
std::cout<<"Enter a word: ";
std::cin>> std::setw ( 10 ) >> word;
for ( int i = 0; word[i] != '\0'; i++ ) {
for ( int j = 0; alphabet[j] != '\0'; j++ ) {
if ( word[i] == alphabet[j] )
std::cout<< values[j] <<' ';
}
}
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Couldn't you have just used the ascii value and then subtracted to get its value in the alphabet?
Sorry my bad, i didn't read well enough. Your either writing a hash routine or weak encryption program aren't ya?
Sauce
Junior Poster in Training
55 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
>Couldn't you have just used the ascii value and then subtracted to get its
>value in the alphabet?
Even if that were a solution, it would still be a poor one. You would be making a non-portable assumption about the character set. This trick is only guaranteed to work with the digit characters, '0' through '9'.
>Your either writing a hash routine or weak encryption program aren't ya?
My bet is for encryption.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>Pretty easy to crack, though.
Actually, if done correctly, the XOR encryption can be used for a one-time pad, which is virtually impossible to crack.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>how can i make in c++ to recognize the 'space' character?
Just add a space to the alphabet and a corresponding value, same as all of the other characters you want to recognize.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Simple, just keep a running total through the loop:
int sum = 0;
for ( int i = 0; word[i] != '\0'; i++ ) {
for ( int j = 0; alphabet[j] != '\0'; j++ ) {
if ( word[i] == alphabet[j] )
sum += values[j];
}
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401