Hi guys, I am attempting to complete an assignment that requires the user to enter in the name, number and points scored for 5 basketball players. My input validation works well with numbers but not the name(string) of the player. As i understand I need to check each char in the string for validation(no numbers or symbols). I am having a difficult time with this. I created a function bool(isLetter) and call that for string validation but that appears to be a bit off as well. Any ideas to help push me in the right direction would be much appreciated. Thanks in advance. Here is my code:
In your validation function you seem to be returning invalid if any of the characters is not a number or a space, which is not what you want. Also note that your block after the if there isn't part of the if; the if if only including the return false you've written after it.
There is such a function as std::isalpha declared in header <cctype> that will make your task very simple.
Here is an example of using it with standard algorithm std::all_of
1 2 3 4 5
inlinebool isValidName( std::string name )
{
return ( std::all_of( name.begin(), name_end(),
[] ( char c ) { return ( std::isalpha( c ) ); } ) );
}
You can substitute the standard algorithm for your loop.
returning false ends the function. none of the following code executes. and the system pause and system exit also might be causing issues. i would suggest removing all of them.
Ok, thanks, I was only adding the system pause so that the console would stay up so I could see if the exit prompt was correct. I thought that was the way using Visual C++ on a window's machine. I traditionally have done this using Macvim and have switched for school. The exit(0) I added to terminate, should it not be there? The reason for it was so that the program terminated rather than clearing the buffer etc, I had confusion on clearing input when the input is tallying for a grand total, so I found it a bit easier for myself to just terminate until I grasped the concept.
This does not work correctly, you have || instead of &&. Why can't a name have a space anyway? (That's actually something to have purposefully allowed by using getline().
Try to avoid system("pause");. A cin.get(); works well, just tell the user to hit enter, and also make sure to clear the buffer before hand (something I think should be done after every extraction anyway).
You should be able to return 0; instead of exit(0). Then again, you should be fixing the cin and letting the user try to input another number.