使用For循环的密码提示符(C ++)

时间:2018-02-19 23:26:28

标签: c++ for-loop

我的代码中的一个小问题是由Alex Allain使用下面的For循环跳转到C ++中的练习题。

以下代码

#include <iostream>
#include <string>
using namespace std;

int main ()
{
    string password;
    for ( int i = 5; i>=0; i-- ) {
        cout << "Please enter your password you have " << i << " attempts remaining: ";
        cin >> password;
    }
    if ( password == "Kent" ) {
        cout << " Password is correct.";
        break;
    } else {
        i--;
        cout << i << " attempts remaining." << endl;
    }

    return 0;
}

我在构建消息{using CodeBlocks}

中的break语句中收到此错误
C:\Users\Documents\Jumping into C++\src\practice 4 (chapter 5 
variant).cpp|23|error: name lookup of 'i' changed for ISO 'for' scoping 
[-fpermissive]|

我使用while循环完成了同样的完全代码没有问题,但是当我使用For循环时,编译器继续进行搜索..任何帮助都表示赞赏:)

1 个答案:

答案 0 :(得分:6)

你应该把if-else放在for循环中:

for ( int i = 5; i>=0; i-- ) {
    cout << "Please enter your password you have " << i << " attempts remaining: ";
    cin >> password;

    if ( password == "Kent" ) {
        cout << " Password is correct.";
        break;
    } else {
        cout << i-1 << " attempts remaining." << endl;
    }
}