gpt4 book ai didi

c - C 中 Do-While 循环的问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:18 25 4
gpt4 key购买 nike

我在编码方面非常新,我正在努力让这段代码循环(直到满足正确的标准.. 大写/小写字母和数字)我是否将 do while 循环放入正确的地方??

非常感谢收到的任何帮助..

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>

main()
{
int i;
int hasUpper, hasLower, hasDigit;
char password[20];

hasUpper = hasLower = hasDigit = 0; // initialising these three variables to false (o)

printf("Please enter a alpha numeric password with upper and lower case\n");
scanf(" %s", password);

do {
for (i = 0; i < strlen(password); i++) {
if (isdigit(password[i])) {
hasDigit = 1;
continue;
}

if (isupper(password[i])) {
hasUpper = 1;
continue;
}

if (islower(password[i])) {
hasLower = 1;
continue;
}
}

printf("Not so good, try again!");
scanf(" %s", password);
} while ((hasDigit) && (hasLower) && (hasUpper)==1);

// This loop will only execute if all three variables are true

if ((hasUpper) && (hasLower) && (hasDigit)) {
printf("Great password!");
}

return 0;
}

最佳答案

您的 while 条件有问题,而且每次尝试后都需要清除变量,并且需要检查失败的打印输出。此外,将您的 scanf() 移到循环的开头会使事情变得更容易,并且无需在初始输入时在循环外添加额外的一个。

#include <stdio.h>
#include <string.h>
#include <stdbool.h> // Use for boolean types

int main(int argc, const char argv[]) { // Correct function signature
int i = 0, plen = 0;
bool hasUpper = false, hasLower = false, hasDigit = false; //Change types to boolean
char password[20] = {0}; // Initialise string with all '\0'

printf("Please enter an alpha-numeric password with upper and lower case\n");

do {
hasUpper = false; // Clear boolean variables for each new password
hasLower = false;
hasDigit = false;

scanf("%s", password);
password[19] = 0; // ensure string is correctly terminated with '\0'
plen = strlen(password); // Get the string length *once* per new password

for (i = 0; i < plen; ++i) {
if (isdigit(password[i])) { // Use 'if...else' in place of 'continue'
hasDigit = true;
}
else if (isupper(password[i])) {
hasUpper = true;
}
else if (islower(password[i])) {
hasLower = true;
}
}

if ((!hasDigit) || (!hasLower) || (!hasUpper)) { // Check the booleans before printing fail message
printf("Not so good, try again!");
for (i = 0; i < 20; ++i) {
password[i] = 0; // Clear the string with all '\0'
}
}
} while ((!hasDigit) || (!hasLower) || (!hasUpper)); // Correct the logic here

printf("Great password!"); // Remove the unneeded boolean check here
return 0;
}

我还会考虑用 if...else if 替换 if...continue 模式,因为使用 continue 是不好的练习。

关于c - C 中 Do-While 循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29124188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com