![](/img/trans.png)
[英]I cant make the asterisk operator overloading it does nothing on the code below it should repeat my string 5 times but it doesnot
[英]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
語句,只需使用帶有if
語句的do-while
循環。 或者更好的是,您可以制作一個單獨的 function 來接收和驗證輸入。 這將使一切更具可讀性。
就像是:
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");
// ...
}
}
將 1 添加到repeat
變量后,您必須保存結果,例如,如下所示:
repeat = repeat + 1
較短的替代方案是
repeat += 1
或者
repeat++
一般來說,在這種情況下,我會使用 for 循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.