Hello all, I am having trouble with the following code. It should be validating whether or not the first letter of a name is alphabetic. However, when I enter an invalid name twice in a row, it accepts the answer the second time, but ignores the first letter.
Heres my output:
What would you like to do?
1. Enter Person information
1
What is person #1's name?
(enter the full name)
8l
Name may not start with non-alphabetic letter. Try again:
!l
What is l's age?
It is disregarding the ! in the name for some reason.
The use of ignore() before getline() is not recommended.
That code is dependent on the existing state of the input buffer, which is here assumed to contain a trailing newline '\n' as a result of some previous cin >> operation.
It would be better to remove the cin.ignore() from here, and instead apply it at the point in the program where the newline was put into the buffer. That is to say, in main().
Actually, I wanted to know how I can make the first letters of the first and last name uppercased. I know I can do
name[0] = toupper(name[0]);
But that only changes the first name to uppercase. How about the last name? I would change the name string into a first name string and last name string, but we are supposed to store it in one string.
I think you could search for the letter after the space and change it to uppercase, but I don't have the experience to do this.
std::string adjust_case( std::string name )
{
bool in_word = false ;
for( char& c : name ) // for each character in name
{
if( std::isalpha(c) ) // if alphabet
{
if(in_word) c = std::tolower(c) ; // if already in a word, convert to lower case
else // beginning of a new word
{
c = std::toupper(c) ; // convert to upper case
in_word = true ; // we are in a word now
}
}
else in_word = false ; // not alpha, we are not in a word now
}
return name ;
}
Use std::sregex_token_iterator to tokenize the std::string using whitespace (and any others) as delimiter(s). Manipulate the iterator returned by the std::sregex_token_iterator ctor to uppercase first letters:
(http://en.cppreference.com/w/cpp/regex/regex_token_iterator)