【发布时间】:2015-08-10 12:48:39
【问题描述】:
在下面的代码中,我有一个 while 语句用于确保输入字符串少于 10 个字符。我已经声明了一个名为cont 的bool,我用它来告诉while 循环在满足我的条件后停止。
#include "stdafx.h"
#include <iostream>
#include <string>
int main()
{
using namespace std;
cout << "Enter a string less than 10 characters long: ";
string teststring;
{
bool cont(false);
//if input is 10 or more characters, ask for input again until it is less
while (!cont)
{
getline(cin, teststring);
if (teststring.length() >= 10)
{
cout << "Too long, try again: ";
}
else
{
cout << "Thank you.\n\n";
cont = true;
}
}
}
return 0;
}
如您所见,我使用了一组{}s 将代码分开,在这些大括号内为cont 变量提供了一个局部范围。我这样做是为了如果我想再次使用那个变量名,我可以重新声明它,当我用完它时,它就被销毁了。
这是一种可接受的做法吗?还是有更好的方法来做我所做的事情?我承认,在这个特定的基本场景中,条件很简单,几乎没有必要,但我可能希望在未来更复杂的循环中这样做。
【问题讨论】:
-
如果要再次使用它,为什么要重新声明它?您可以在循环之后将其设置为 false 并根据需要重用它(没有范围的东西)
-
如果您发现自己需要这样做,那么您在一个函数中的代码太多了。你应该把它分解成一个单独的函数。
-
@T.C.我不确定这是否具有您认为的效果。 ideone.com/qt3D8h
-
@DanAllen 好点。实际上,它每次迭代都会创建一个新变量(并重新初始化它),这与
for不同,因此可能会使用while(bool b = some_function()) { /* run until some_function returns false */ }。 -
@T.C 改变了一切!幸运的是,我还听到了其他一些不错的建议,所以我现在当然有选择了!
标签: c++ loops while-loop curly-braces