当我尝试从用户处获取用户名时,我会进行以下操作:
#include <iostream>
using namespace std;
void main(){
char *usrn=new char[20]; //Max username length of 20 alfanumeric characters
std::string usrn_str;
while (true){
std::cout << "Enter the username(3-20 characters): ";
cin.clear();
cin.ignore();
std::cin.getline(usrn,22);
usrn_str=usrn;
if ((usrn_str.length())<3){
cout << "Introduced username too short!" << endl;
}
else if ((usrn_str.length())>=21){
cout << "Introduced username too long!" << endl;
}
else {
cout << usrn_str.c_str() ;
}
}
}
无论如何,当引入比允许的用户名更大的用户名,即25时,它会向我显示引入的用户名太长的消息,但在下一个循环中,我无法再次输入用户名,因为它需要我在上述例子中输入了最后5个字符。总结一下,如果我输入30长度的用户名,它会丢弃前20个用户名,并将最后10个用户名设置为用户名,当我想要用户名时,直到我得到3-20长度的用户名。
我该如何实现它?任何帮助表示赞赏。
答案 0 :(得分:1)
使用std::getline()
读取整个用户输入(用户输入是基于行的)。然后针对输入行进行验证检查。
bool finished = false;
std::string name;
do
{
if (std::getline(std::cin, name))
{
// You have successfully read one line of user input.
// User input is line based so this is usually the answer to
// one question.
//
// Do your validation checks here.
// If the user entered data that checks out then set
// finished to true.
}
else
{
// There was a problem reading the line.
// You need to reset the stream to a good state
// before proceeding or exit the application.
}
}
while(!finished);