How can i set up an error check so only letters are entered? I know how to do it for numbers but have no idea how to make it so it only allows a-z inputs.
#include <iostream>
#include <cctype>
int main()
{
char ch ;
// std::isalpha(ch) : is character ch an alphabetic character?
// !std::isalpha(ch) : is character ch something other than an alphabetic character?
// http://en.cppreference.com/w/cpp/string/byte/isalphawhile( std::cout << "[a-z]? " && std::cin >> ch && !std::isalpha(ch) )
{
std::cout << "please enter an alphabetic character\n" ;
}
// http://en.cppreference.com/w/cpp/string/byte/tolower
ch = std::tolower(ch) ; // convert to lower case
std::cout << "the character entered (in lower case) is: " << ch << '\n' ;
}
#include <iostream>
#include <cctype>
int main()
{
std::string str ; // initially empty
const std::size_t nchars_needed = 6 ;
while( str.size() < nchars_needed )
{
char ch ;
while( std::cout << "[a-z]? " && std::cin >> ch && !std::isalpha(ch) )
{
std::cout << "please enter an alphabetic character\n" ;
}
// uncomment this line to convert ch to lower case before appending to the string
// ch = std::tolower(ch) ;
str += ch ; // append character to string
std::cout << "the string so far is: " << str << '\n' ;
}
for( char& c : str ) // for every char in string str
c = std::tolower(c) ; // convert it to lower case
// another option would be to append to the string after converting to lower case
// if we uncomment line 18, this loop would not be needed.
std::cout << "the string with characters converted to lower case: " << str << '\n' ;
}