Hello, so my question is how do you make an string input that will only allow a specific format. Like a username thing. It won't allow spaces or symbols or numbers stuff like that.
#include <iostream>
#include <regex>
#include <string>
bool isValidUserName(const std::string& name)
{
constunsigned minLength = 4 ;
std::regex allowable("[a-zA-Z][_[:alnum:]]*") ;
return name.length() >= minLength && std::regex_match(name, allowable) ;
}
int main ()
{
std::string userName;
bool isInvalidName = true ;
while ( isInvalidName )
{
std::cout << "Username> " ;
std::getline(std::cin, userName) ;
if ( (isInvalidName = !isValidUserName(userName)) )
{
std::cout << "User name must be at least 4 letters long. The first letter must be a letter\n""of the alphabet. Subsequent characters may be a letter of the alphabet, a\n""number or an underscore.\n\n" ;
}
}
std::cout << "Your user name is \"" << userName << "\"\n" ;
}
Umm..no I was not comparing the two items. I was setting it equal to it. As in getting a new string if the old one was invalid...and I suppose there are probably better ways to do it than the while loop I did but I was giving you an idea not a "please copy/paste me then tell me if the code works or not" :p and yeah what did you expect it to do after compiling display hello world? It asks for an input and if the input is not all letters then it displays an error message and asks for the user to enter another username.
Also I don't know what I was thinking with that while loop and the string before. Try this instead for lines 24 and 25 while( !valid_name( input() ) ) std::cout << "invalid username!" << std::endl;
If you want to set the valid "input" to a string then maybe do this
but I wouldn't suggest it because I think it looks very ill-formed to me. Although using a function as a parameter prob isn't the best idea anyways so people probably will get mad at me suggestions the code about 5 lines earlier...
**edit
btw you just need to enable c++11 go to the compiler settings and then flags and put this
-std=c++11
GCC's regex implementation was still quite buggy for versions 4.7.x. I don't know if that changed for 4.8. If you're stuck with a buggy implementation, you can always use boost.