Trying to convert a username into how many characters it is (ie the name Bob = 3) to do further calculation further down to multiply by age. I feel Im so close
#include <iostream>
#include <string>
usingnamespace std;
int main(){
string fullname;
int a = fullname.length();
int age;
int enrol;
int pin;
cout <<"Welcome to the our App\n";
cout <<"Please enter your full name:\n";
cin >> fullname;
cout <<"Please enter your age:\n";
cin >> age;
cout <<"Please enter your enrolment number:\n";
cin >> enrol;
cout <<"Generating pin...\n";
pin = (a*age)*enrol;
cout <<"Hi " << fullname << ". Your account " << enrol << " has been created.\nYour unique pin number is " << pin;
return 0;
So basically the question/ input is asking for the users full name and find the length of name so if name entered is John my code converts that to integer 4 to be multiplied by age input.
Im having trouble when users name is John Doe this should output 7 (ignoring the space) so while trying to get this to work I was cheating a little bit and asking for first name first, then asking for surname and adding together
But I also need it to work if someone had 3 names or a double barrelled name etc.
so your code helps but it includes the space which I dont want
Edit:
I have it working with this to subtract spaces but doesnt work with characters (John Bob-Doe returns 11, counting the - which im not to bothered with at the moment)
1 2 3 4 5
cout <<"Please enter your full name:\n";
getline(cin, fullname);
//cin >> firstname;
fullname.erase(remove(fullname.begin(), fullname.end(), ' '), fullname.end());
int fname = fullname.length();
You don’t need to erase anything, just count the things that matter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <algorithm>
#include <ciso646>
#include <cctype>
#include <string>
int main()
{
std::string fullname;
std::cout << "Please enter your full name: ";
getline( std::cin, fullname );
auto name_length = std::count_if( fullname.begin(), fullname.end(), []( char c )
{
return !(c & 0x80) and !std::isspace( c );
} );
std::cout << "You have " << name_length << " letters in your name.\n";
}
The weird []( char c ) { ... } thing is a lambda — I could have used a normal function instead but this just keeps all relevant code in one spot.
The !(c & 0x80) clause is for UTF-8 awareness — making your non-whitespace letter counting thing able to count a multibyte UTF-8 sequence as a single code-point value (which is how it is displayed, even though it is made up of multiple characters).