C ++用户输入限制,具有适当的重试而没有“goto” [英] C++ user input restriction with proper retry without "goto"
问题描述
我有以下代码:
qstn:
cout << "Input customer's lastname: ";
getline(cin, lname);
if (lname.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ") != string::npos) {
cout << "You can only input alpha here!\n";
cin.clear();
goto qstn;
} else if (lname.empty()) {
cout << "Please enter your firstname!\n";
cin.clear();
goto qstn;
}
int lnamel = lname.length();
int strl = str.length();
int is = 0;
for (int i = 1; i < strl;) {
i++;
is++;
if (lname[i] == lname[is] && lname[i] == ' ' || lname[0] == ' ') {
cin.clear();
cout << "Please input your lastname properly!\n";
goto qstn;
}
}
// next question here
m有一个很难的时间在思考什么是正确的逻辑,以避免
goto语句,因为我大学时我正在使用它,但有人在这里说,
不好使用它在所有原因可能毁了我的代码。
I'm having a hard time on thinking what will be the proper logic to avoid the goto statement, since I was college I was using it but someone here said that it's not good to use it at all cause it might ruin my code.
我尝试使用do while循环,但它不像goto一样流畅。
I tried using the do while loop but it's not smooth as goto.
请帮助!
推荐答案
使用函数:
bool getLastName(string & lname,
string & str)
{
cout << "Input customer's lastname: ";
getline(cin, lname);
if (lname.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ")
!= string::npos)
{
cout << "You can only input alpha here!\n";
cin.clear();
return false;
}
else if (lname.empty())
{
cout << "Please enter your firstname!\n";
cin.clear();
return false;
}
int lnamel = lname.length();
int strl = str.length();
int is = 0;
for (int i = 1; i < strl;)
{
i++;
is++;
if (lname[i] == lname[is] && lname[i] == ' ' || lname[0] == ' ')
{
cin.clear();
cout << "Please input your lastname properly!\n";
return false;
}
}
return true;
}
所有我在这里做的是替换 goto
与 return false
。如果程序使它到函数的结尾, return true
。在while循环中调用函数:
All I've done here is replace the goto
s with return false
. If the program makes it to the end of the function, return true
. Make the function call in a while loop:
while (!getLastName(lname, str))
{
// do nothing
}
这不仅代码化了代码,但它把它分解成好,小,容易管理的片段。这称为程序编程。
Not only does this de-spaghettify the code, but it breaks it up into nice, small, easy to manage pieces. This is called procedural programming.
这篇关于C ++用户输入限制,具有适当的重试而没有“goto”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!