使用花括号来隔离我想在C++中多次使用的变量

Eri*_*tor 6 c++ loops curly-braces while-loop

在下面的代码中,我有一个while语句用于确保输入字符串少于10个字符.我已经声明了一个bool被叫cont,我用它来告诉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;
}
Run Code Online (Sandbox Code Playgroud)

正如你在那里看到的那样,我使用了一组{}s来分离代码,为cont变量赋予这些大括号内的局部范围.我做了这个,所以如果我想再次使用那个变量名,我可以重新声明它,当我完成它,它就被破坏了.

这是可接受的做法吗?或者有更好的方法来做我做过的事情吗?我承认在这个特定的基本场景中,条件很简单,几乎没有必要,但我可能希望将来为更复杂的循环做这件事.

Per*_*xty 1

这显然是一个玩具箱,但这是一个很好的做法,并且“独立”块就是为此目的而存在的。我碰巧相信它们是构造长函数的更好方法,而不是将其分解为(在许多情况下)没有单独目的的成员。

在这种情况下,您可以提供一个更快、更清晰、更安全的程序,特别是如果有一个注释(可能是一行)介绍每个块。

但在这种情况下,您可能会考虑:

    for ( bool cont(false);!cont;)
Run Code Online (Sandbox Code Playgroud)

其效果相同。语句中声明的变量for(.;.;.)仅限于该语句的范围。

在这种情况下,您可以使用以下方法来躲避整个变量:

    for(;;) //<--- Canonical formulation for 'infinite' loop.
    {
        getline(cin, teststring);

        if (teststring.length() >= 10)
        {
            cout << "Too long, try again: ";
        }
        else
        {
            cout << "Thank you.\n\n";
            break; //<--- Escapes the loop.
        }

    }
Run Code Online (Sandbox Code Playgroud)

脚注(回应评论):

您应该将for循环视为循环上的“语法糖” while。它们的性能等没有什么不同,只需选择可读性最好的一个即可。for(;cond;)只是看起来很有趣。

可能会有一点点的性能优势,break但我碰巧认为它在许多情况下实际上更简单且更具可读性。

如果代码更复杂,可能会有更多“循环结束”代码,因此它会变成:

for(bool cont(false);!cont;) {

    //Complex code with multiple 'exit' conditions...

    if(!cont) {
        //Go round again code that won't fit nicely in last term of for loop...
    }
}
Run Code Online (Sandbox Code Playgroud)

而使用break只是让“快速退出”更容易理解。他们(广泛)不被认为有“恶业”,goto因为他们“去”了一个非常明确定义的执行点。