Reputation: 67
do{
std::cout << "Name? \n";
std::cin >> Name1;
getchar();
}while();
How do I check if the user input is a name and not a number? I tried cin.fail() but it doesnt seem to work. basically all I want to do is to loop if the user input is a character, like: , . + - etc... or numbers(0, 1 ,2 ,4...), would be nice if there is a way to just do while(Name1 != std::string)
Upvotes: 0
Views: 935
Reputation: 11
As others have suggested, your problem can be approached with different levels of difficulty.
If you define a valid name as a string that does not contain special characters or numbers (i.e. +-. 0...9 etc) then you can write a function that checks if the entered string contains only alphabetic characters. One way you can do that is using std::isalpha
If you've read the linked reference for std::isalpha
, you'll see that it checks if a given character is an alphabetic character. You also have there the implementation for the method count_alphas(const std::string& s)
that counts how many characters you have in a string.
You can check the reference std::count_if
here and you need to include <algorithm>
to use it.
int count_alphas(const std::string& s)
{
return std::count_if(s.begin(), s.end(), [](unsigned char c){
return std::isalpha(c);
});
}
With this method, you can complete your code as follows
do{
std::cout << "Name? \n";
std::cin >> Name1;
getchar();
}while(Name1.length() != count_alphas(Name1));
If the condition is true, this means you have less alphabetical characters in your string than the length of your string, so your name is not what you defined to be valid.
You can also use std::find_if
instead of the std::count_if
to directly return false if you've found a non-alphabetical character, you can try implementing this yourself.
If you are not comfortable with using algorithms or lambdas, you can store what you don't
don't want to appear in your valid name into a vector of strings and iterate through the input name to see if if contains any of the stored elements of the vector. If it does, it's now a valid name.
Upvotes: 1
Reputation: 31
You can use regex to check if the input is valid.
#include <regex>
#include <string>
#include <iostream>
int main()
{
std::regex name("[[:alpha:]]+"); // Match 1 or more alphabetic characters
while (true)
{
std::string input;
std::cout << "Enter name: " << std::endl;
std::getline(std::cin, input);
if (std::regex_match(input, name))
std::cout << "Input is a name" << std::endl;
else
std::cout << "Input is not a name" << std::endl;
}
return 0;
}
You can find the syntax for the regex here and the c++ reference guide here
Upvotes: 0