我不明白为什么用户在输入中输入-1时do-while循环没有终止。只需忽略内部while循环之后的所有内容。我知道问题出在while循环中的某个地方。我就是看不出来。
int main()
{
srand(time(0));
int input;
std::string pass, company, timeS;
do
{
std::cout << "Enter password length: ";
std::cin >> input;
while(input < 8 || input > 16)
{
if(!std::cin)
{
std::cin.clear();
std::cin.ignore(100, '\n');
}
std::cout << "Password length must be between 8 and 16.\nEnter password length: ";
std::cin >> input;
}
std::cout << "Enter company name: ";
std::getline(std::cin, company);
pass = passGen(input);
time_t now = time(0);
auto time = *std::localtime(&now);
std::stringstream ss;
ss << std::put_time(&time, "%Y %b %d %H:%M:%S %a");
timeS = ss.str();
std::cout << "You passoword: " << pass << std::endl;
writeFile(pass, company, timeS);
}while(input != -1);
return 0;
}提前感谢!
发布于 2019-11-09 17:45:30
内部while循环永远不会终止,因为条件为对于-1将始终为真。
int main()
{
srand(time(0));
int input;
std::string pass, company, timeS;
do
{
std::cout << "Enter password length: ";
std::cin >> input;
while((input < 8 && input>=0)|| input > 16)
{
if(!std::cin)
{
std::cin.clear();
std::cin.ignore(100, '\n');
}
std::cout << "Password length must be between 8 and 16.\nEnter password length: ";
std::cin >> input;
}
if (input>0){
std::cout << "Enter company name: ";
std::getline(std::cin, company);
pass = passGen(input);
time_t now = time(0);
auto time = *std::localtime(&now);
std::stringstream ss;
ss << std::put_time(&time, "%Y %b %d %H:%M:%S %a");
timeS = ss.str();
std::cout << "You passoword: " << pass << std::endl;
writeFile(pass, company, timeS);
}
}while(input != -1);
return 0;
}发布于 2019-11-09 18:03:05
在此循环中,等待8到16之间的数字:
while(input < 8 || input > 16)
{
if(!std::cin)
{
std::cin.clear();
std::cin.ignore(100, '\n');
}
std::cout << "Password length must be between 8 and 16.\nEnter password length: ";
std::cin >> input;
}猜猜,什么东西永远不会从那个循环中出来?对,-1 !!=)
发布于 2019-11-09 18:13:29
希望这能回答你的问题:
int main()
{
srand(time(0));
int input;
std::string pass, company, timeS;
// do
// {
while(true){
std::cout << "Enter password length: ";
std::cin >> input;
if(input == -1){
break;
}
while(input < 8 || input > 16)
{
if(!std::cin)
{
std::cin.clear();
std::cin.ignore(100, '\n');
}
std::cout<< "=====>>>" << std::endl;
std::cout << "Password length must be between 8 and 16.\nEnter password length: ";
std::cin >> input;
}
std::cout << "Enter company name: ";
std::getline(std::cin, company);
pass = passGen(input);
time_t now = time(0);
auto time = *std::localtime(&now);
std::stringstream ss;
ss << std::put_time(&time, "%Y %b %d %H:%M:%S %a");
timeS = ss.str();
std::cout << "You passoword: " << pass << std::endl;
writeFile(pass, company, timeS);
}
// }while(input != -1);
return 0;
}只需使用
while(true){
//getting length of password
if(input == -1){
break;
}
//rest of the logic
}https://stackoverflow.com/questions/58778013
复制相似问题