2014-03-03 100 views
0

我正在为项目输入字符串,如名称和密码。我试图通过添加一个输入验证来证明它,通知用户只输入一个单词。问题是我不知道如何使这种输入验证这里是什么样的输入会是什么样子防止字符串输入空间C++

int main(){ 
    string firstname, lastname, password; 
    cout<<"Enter in your first name:"<<endl; 
    cin>>firstname; 
    cout<<"Now Enter your last name:"<<endl; 
    cin>>lastname; 
    cout<<"Lastly enter a password"<<endl; 
    cin>>password 


    return 0; 



} 

为例现在,我真的想为密码变量输入验证这样用户就不会尝试输入两个字或更多的密码。

回答

0

基本上,你不希望密码有任何空格。因此,在密码中搜索一个空格;如果找到,请重新输入。

if (password.find (' ') != string::npos) 
{ 
    cout << "Password cannot have spaces!" << endl; 
} 
0

您可以遍历password中的字符并检查其中是否有空格。如果您发现空间(或任何其他无效字符)拒绝密码。

BOOL is_valid = TRUE; 
for(std::string::iterator chr = password.begin(); chr != password.end(); ++chr) 
{ 
    if (*chr == ' ') 
     // add more conditions here if you'd like.. 
    { 
     // invalidate the password 
     is_valid = FALSE; 
     break; 
    } 
} 

if(!is_valid) 
{ 
    // handle the case when the password is not valid.. 
} 

以上是好的,因为它给你检查每个字符,并在每一步检查多个规则的机会,但如果你真的只希望找到password是否包含空格,那么你可以使用the find method

BOOL is_valid = (str.find(' ') == std::string::npos);