密码提示使用循环(C )

Password Prompt using For Loop (C++)

本文关键字:循环 提示 密码      更新时间:2023-10-16

我的代码中有一个小问题,从练习问题中使用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;
}

我在下面的Break语句中遇到此错误

C:UsersDocumentsJumping into C++srcpractice 4 (chapter 5 
variant).cpp|23|error: name lookup of 'i' changed for ISO 'for' scoping 
[-fpermissive]|

我使用段循环进行了相同的精确代码,没有问题,但是当我使用循环时,编译器会进行狩猎。

您应该将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;
    }
}