-
Type Casting?
Ok what in looking to do is for the user to imput any givin number of chars, then in turn convert those chars in to ints.
Actually not just any ints its sequenced into multiples of six like eg. (A=6, B=12, C=18,... Z=156)
im thinking type casting might be the way to go but there are other factors
I also want to, once the letters are recieved and converted, the sum of all the imputed/converted values must be calculated.
Now..im thinkin like going
char FirstLetterEntered, SecondLetterEntered,Third ......ect
//get the imput
Then mabey...
if ( FirstLetterEntered == "A"||"a")
FirstLetterEntered = 6; //would have to cast here??
But i would have to do it for every one and then again for the second and so on , I know there is a better way i just need some structuring advice
-
Here's one way to do it.
Declare FirstLetterEntered as an int eg.
int FirstLetterEntered;
then assign the user's input character to FirstLetterEntered, eg.
FirstLetterEntered = getch(); //getch() is not ANSI compliant
Code:
if( (FirstLetterEntered >=97 && FirstLetterEntered <=122) || (FirstLetterEntered >=65 && FirstLetterEntered <= 90) )
{
if(FirstLetterEntered >=97 && FirstLetterEntered <=122)
{
FirstLetterEntered = (FirstLetterEntered - 96) * 6;
break;
}
if(FirstLetterEntered >=65 && FirstLetterEntered <=90)
FirstLetterEntered = (FirstLetterEntered - 65) * 6;
}
just plonk that in a loop, and there you go
-
one flaw:
Code:
if( (FirstLetterEntered >=97 && FirstLetterEntered <=122) || (FirstLetterEntered >=65 && FirstLetterEntered <= 90) )
{
if(FirstLetterEntered >=97 && FirstLetterEntered <=122)
{
FirstLetterEntered = (FirstLetterEntered - 96) * 6;
break;
}
if(FirstLetterEntered >=65 && FirstLetterEntered <=90)
FirstLetterEntered = (FirstLetterEntered - 64) * 6;
}
-
Here's my solution. It could easily be pulled down a bit, but its fun to work with :).
Code:
#include <valarray>
#include <iostream>
#include <vector>
#include <numeric>
#include <cctype>
//Conversion
inline unsigned char convert( unsigned char ch ) { return tolower(ch) - 'a' + 1; }
int main( void )
{
std::vector< unsigned char > vec; //Need unsigned chars here so we don't overflow
unsigned char ch;
/* Debugging, make sure 'a' == 1
for( char ctest = 'a'; ctest <= 'z'; ++ctest )
std::cout << static_cast<int>(convert( ctest )) << " ";
std::cout << std::endl;*/
while( std::cin >> ch ) //Read until a non-number character pops in
{
if( !isalpha( ch ) ) break;
vec.push_back( convert(ch));
}
std::valarray<unsigned char> array(vec.begin(),vec.size()); //Create the powerful std::valarray for quick computation
array *= static_cast<unsigned char>(6); //Need to cast, otherwise, it thinks 6 is an int
int number = std::accumulate( &array[0], &array[array.size()], 0 ); //Add everthing together
std::cout << number << std::endl; //Output the sum
return 0;
}