首页 > 解决方案 > C ++中的意外无限循环

问题描述

我在一个项目中工作,任务是制作注册功能,所以当我在密码功能中尝试几个测试用例时,当我尝试输入无效密码而没有机会重新输入密码时,我陷入了无限循环. 提前致谢...

#include <iostream>
#include <string>
#include <cstring>
#include <conio.h>
#include <stdio.h>
using namespace std;
#define size 40
int main(){
    bool flag = true;
    while (flag){
        bool flagS = false, flagN = false; int count = 0;
        char password[size] = { 0 };
        cout << "Type your Password .....\n Note :: Must be more than 8 characters including at least one number and one special character...\n";
        cin.get(password, size);
        count = strlen(password);
        for (int z = 0; z < count; z++){
            if (password[z] >= 48 && password[z] <= 57)
                flagN = 1;
            if ((password[z] >= 33 && password[z] <= 47) || (password[z] >= 58 && password[z] <= 64))
                flagS = 1;
        }

        if ((flagS == 1) && (flagN == 1) && (count >= 8))
        {
            cout << "Valide Password ...\nCongrats!! ..you created a NEW account.." << endl;
            flag = false;
        }
        else
        {
            cout << "invalide password..\nPlease try again..\n";
            flag = true;
        }
    }
}

标签: c++while-looppasswordsinfinite

解决方案


您必须在循环cin内部编写。while这将解决您的问题:

#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
#define size 40
int main(){
    bool flag = true;
    bool flagS = false, flagN = false; int count = 0;
    char password[size] = { 0 };

    cout << "Type your Password .....\n Note :: Must be more than 8 characters including at least one number and one special character...\n";

    while (cin >> password && flag){

        count = strlen(password);
        for (int z = 0; z < count; z++){
            if (password[z] >= 48 && password[z] <= 57)
                flagN = true;
            if ((password[z] >= 33 && password[z] <= 47) || (password[z] >= 58 && password[z] <= 64))
                flagS = true;
        }

        if ((flagS) && (flagN) && (count >= 8))
        {
            cout << "Valide Password ...\nCongrats!! ..you created a NEW account.." << endl;
            flag = false;
        }
        else
        {
            cout << "invalide password..\nPlease try again..\n" << "Type your Password .....\n Note :: Must be more than 8 characters including at least one number and one special character...\n";;
            flag = true;
        }
    }
}

推荐阅读