我正在一个项目中,任务是进行注册功能因此,当我在密码功能中尝试多个测试用例时,当我尝试输入无效的密码而没有给我重新输入密码的机会时,我陷入了无限循环。预先感谢...
#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;
}
}
}
您必须在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;
}
}
}
std::istream::get
不会从流中删除换行符。这意味着对std::istream::get
的下一次调用会立即找到换行符,而不将任何内容读入缓冲区,设置故障位,然后返回。因为现在立体声处于失败状态,所以所有后续读取都会立即失败。您可以std::istream::get
换行符,但是更直接的方法是使用cin.ignore()
,因为它会为您删除换行符。
始终在IO事务后测试流状态以确保成功。
旁注:
[首选将std::istream::getline
和std::istream::getline
用于原始字符数组和使用它们的函数。如果提供的缓冲区太小,std::string
和std::getline
都将流标记为失败。提供给std::istream::get
的std::istream::getline
将被调整大小,因此,只要您有剩余的动态存储,就可以解决缓冲区溢出问题以及为防止这些问题而引发的错误。如果系统无法为string
分配足够大小的缓冲区,则会引发异常以使您意识到问题。
[首选使用字母,例如std::getline
代替原始ASCII码。一方面,即使最原始的程序员也可以立即认识到string
的意图,并且始终有可能实现不使用ASCII作为默认编码。