I'm writing a program for an assignment. Part of it is I need to validate a certain string so it only contains alphabetical characters but I can't figure it out. This was a test code I used to attempt to write a validator.
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
bool isValidName(string str);
string str[20];
main() {
cout << "enter name\n ";
getline(cin, str[1]);
isValidName(str[1]);
cout << isValidName << endl;
system("pause");
}
bool isValidName(string str) {
for (int i = 0; i < (int)str.length(); i++) {
if (!isalpha(str[i])) {
return false;
break;
}
return true;
break;
}
}
It doesn't matter what kind of character I put it, it will always return 1 :o(
(Thanks to Paul Rooney for fixing the indentation)
Another way of writing your validation proc would be:
bool isValidName(const std::string& str)
{
return std::all_of(str.begin(), str.end(), isalpha);
}
In your function:
bool isValidName(string str)
{
for(int i=0;i<(int)str.length();i++)
{
if (!isalpha(str[i]))
{
return false;
break; // breaking here is useless, you've already returned.
}
return true; // this is not in the right spot. you return true
// if the first character is alpha !!
}
return true; // <-- should be here.
}
Proper indentation makes these errors easy to spot.
One of the problems was you were not printing the return of the function, you were printing the the function variable. cout << isValidName << endl; //wrong
you were also already making returning in the first character check, I hope the code below can help you
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
bool isValidName(string str);
string str;
main(){
cout << "enter name\n ";
getline(cin, str);
cout << isValidName(str) << endl;
}
bool isValidName(string str) {
for(int i=0;i<(int)str.length();i++) {
if (!isalpha(str[i])) {
return false;
}
}
return true;
}
fixed thanks to rooney
Another elegant solution is to use regular expressions to validate your input.
#include <iostream>
#include <string>
#include <regex>
bool isValidName(const std::string& str)
{
if (std::regex_match(str, std::regex("[[:alpha:]]*")))
return true;
return false;
}
int main()
{
std::string s("aaASd");
std::cout << isValidName(s) << std::endl;
std::string s1("ss23d");
std::cout << isValidName(s1) << std::endl;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.