我希望我的代码重复 3 次,但循环没有结束。有谁知道我该如何解决这个问题?

I want my code to repeat 3 times but the loop does not end. Does anyone know how I could fix this issue?

代码如下:

    #include <stdio.h>
    #include <string.h>
    #include <conio.h>
    #include <iostream>
    #define repeat(n)
    #define endrepeat

    int main()
    {
    int login;
    
    char Username [4];
    char Password [4];
 
    printf("\t\tPlease enter your user name: ");
    scanf("%s", Username);
    printf("\t\tPlease enter your user password: ");
    scanf("%s", Password);

    if (strcmp (Username,"Jane")==0 && strcmp(Password,"1234")==0 || 
    strcmp(Username,"Arin")==0 && strcmp (Password,"3201")==0 || strcmp 
    (Username,"Jake")==0 && strcmp (Password,"4312")==0 || strcmp 
    (Username,"Jazz")==0 && strcmp (Password,"4456")==0)
    {
    printf("ACCESS GRANTED");

    system("CLS");
    getch();
    }
    
    else
    {
    printf("INVALID USERNAME OR PASSWORD ENTERED.\n");
    printf("\t\tPlease enter your user name: ");
    scanf("%s", Username);
    printf("\t\tPlease enter your user password: ");
    scanf("%s", Password);
    }
    int repeat;
    repeat = 0;
    do  {
    printf("INVALID USERNAME OR PASSWORD ENTERED.\n");          
    printf("\t\tPlease enter your Username: ");
    scanf("%s", Username);
    printf("\t\tPlease enter your password: ");
    scanf("%s", Password);
    repeat + 1 ;
    } while(repeat<3);
    endrepeat;
    
    return 0;
    }

我希望代码在退出前重复 3 次。当我尝试 运行 代码时,它会不断重复。我是编码新手,很抱歉,如果它很容易解决。 :) 我尝试过使用不同的重复方法,但我仍然遇到同样的问题。

像这样增加 repeat 变量:

repeat = repeat + 1;

repeat += 1;

repeat++;

if语句中使用括号来分隔逻辑,避免得到错误的结果,像这样:

if ((strcmp(Username,"Jane") == 0 && strcmp(Password,"1234") == 0) || 
(strcmp(Username,"Arin") == 0 && strcmp(Password,"3201") == 0) || 
(strcmp(Username,"Jake") == 0 && strcmp(Password,"4312") == 0) || 
(strcmp(Username,"Jazz") == 0 && strcmp(Password,"4456") == 0))
{

摆脱 else 语句并简单地使用 do-while 循环和里面的 if 语句。或者更好的是,您可以创建一个单独的函数来接收和验证输入。这将使所有内容更具可读性。

类似于:

bool requestInput()
{
   printf("\t\tPlease enter your Username: ");
   scanf("%s", Username);
   printf("\t\tPlease enter your password: ");
   scanf("%s", Password);

   if ((strcmp(Username,"Jane") == 0 && strcmp(Password,"1234") == 0) || 
       (strcmp(Username,"Arin") == 0 && strcmp(Password,"3201") == 0) || 
       (strcmp(Username,"Jake") == 0 && strcmp(Password,"4312") == 0) || 
       (strcmp(Username,"Jazz") == 0 && strcmp(Password,"4456") == 0))
   {
       return true;
   }

   printf("INVALID USERNAME OR PASSWORD ENTERED.\n");
   return false;
}


int main()
{
   bool accessGranted;
   int repeat = 0;

    do {
        accessGranted = requestInput();
        repeat++;
    } while(repeat<3 && !accessGranted);

    if(accessGranted)
    {
       printf("ACCESS GRANTED");
       // ...
    }
}

repeat 变量加 1 后,您必须保存结果,例如,像这样:

repeat = repeat + 1

较短的替代方案是

repeat += 1

repeat++

一般来说,我会在这种情况下使用 for 循环。