I am trying to figure out how to write a program that will output
"What is your name? Sam
Your name score is: 23"
Something like that.
I would like to make a=1, b=2, c=3, d=4 ... z=26.
When someone inputs their name with keyboard, the program will convert those letters into numbers 1~26 and add them up.
#include <iostream>
usingnamespace std;
int main ()
{
char name;
int result;
int a=1, b=2, c=3, d=4, e=5;
cout<<"What is your name: ";
cin>>name;
cout<<endl;
result = name;
cout<<result<<endl;
system ("pause");
return 0;
}
This isn't an assignment or anything, just something I wanted to challenge myself to try. I took a C++ course back in 2010, but forgot most of it. I am planning to write a code for making weekly schedule after this one. But seems like I am far away from that.
will give you required number provided that all letters in the alphabet folow each other.
For example
1 2 3 4 5 6 7 8
std::string s( "This is your name" );
int number = 0;
for ( std::string::size_type i = 0; i < s.size(); i++ )
{
number += std::toupper( s[i] ) - 'A' + 1;
}
The loop can be written even simply
for ( auto c : s ) number += std::toupper( c ) -'A' + 1;
I think the part that I don't understand is how I could take an input that is unknown, and make it into an expression to add the letters among the input.
Like, if someone inputs Sam, how do I convert that to 19 1 13, then add 19 + 1 + 13.
#include <iostream>
#include <string>
#include <cstdlib>
#include <cctype>
usingnamespace std;
int main ()
{
string name;
cout << "What is your name: ";
cin >> name;
int result = 0;
for ( auto c : name ) result += toupper( c ) -'A' + 1;
cout << endl << result << endl;
system( "pause" );
return 0;
}
I tried to run that on my dev C++ but it gave me error saying "expected primary -expression before "auto" and expected ';' before "auto"and expected ')' before ';' token. this is for "for ( auto c : name ) result += std::toupper( c ) -'A' + 1; "
for ( string::size_type i = 0; i < name.size(); i++ )
{
result += toupper( name[i] ) - 'A' + 1;
}
does that line of code take the letters from variable name (ex: s = 19 a =1 m=13) and then subtract A value which is 1 (ex: s=19-1 a=1-1 m=13-1) then +1 gives a +1 value to the letters that was input.
'A' - 'A' is equal to zero. So 'A' -'A' + 1 is equal to 1. 'B' - 'A' is equla to 1. So 'B' - 'A' + 1 is equal to 2. And so on provided that all letters follow each other.