gpt4 book ai didi

c - 如何检查以下数组是否包含这些字符?

转载 作者:行者123 更新时间:2023-12-02 01:23:28 24 4
gpt4 key购买 nike

所以我有一个名为密码的数组。我将数组初始化为:char password[3] = "",然后使用 while 循环填充它,一次获取一个字符。正确的密码是123。

以下用于检查密码是否为 123 的语句有效:

 if (password[0] == '1' && password[1] == '2' && password[2] == '3')

但我想使用类似的东西:

if (password[3] == {1,2,3})

行数更少,更容易理解。我似乎遇到了这个特定语法错误。我也尝试过

if (password == "123")

但它不接受 123 作为正确的密码。我不确定它在c中是否相同,但在c++中该字符串将以斜杠0结尾,所以我尝试在末尾添加它,再次不起作用。

有没有办法编写它,这样我就不必使用“与”门?

感谢您的帮助。

更新的代码:

char password[4] = "";
int c = 0;
int flg;

void main(void)
{
LATC = 0x00;
TRISC = 0x0b10000000;

//Clear Port B for now
LATB = 0x00;
TRISB = 0x00;


OpenUSART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE &
USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_HIGH, 64);


putrsUSART( " Welcome to your lock program. \r\n " ); // Send the string
Delay10KTCYx(400); // Delay between data transmissions
noPass = 1;

while(noPass == 1)
{
putrsUSART(" \r\n\n Please type the password in: ");

while (c<=2)
{
while(BusyUSART());
// wait for user input
while (!DataRdyUSART());
//get string from terminal
password[c] = getcUSART(); //read a byte from USART

putrsUSART("\r\n\n You typed: ");
//Write a string from program memory to the USART
putcUSART(password[c]);

putrsUSART("\r\n\n");
c++;
}

//if (password[0] == '1' && password[1] == '2' && password[2] == '3' )
if (strcmp(password, "123") == 0)
//unlock
{
putrsUSART("\r\n\n Correct Pasword \r\n\n");
//short time to unlock, set solenoid, then delay it,
//then reset it so it locks again.
Delay10KTCYx(1000); // Delay between data transmissions
c = 0;
noPass = 0;
}
else
{
putrsUSART("\r\n\n Wrong password, please try again \r\n\n");
c = 0;
}
}

}

最佳答案

请注意,password[3] 只能包含长度不超过 2 的字符串,因为您需要考虑 NUL 字符串终止符。但即使是 3 对于密码来说也有点短。

所以你至少需要

char password[4] = "";

并且您必须确保将长度超过 3 个字符的密码复制到 password

进一步的字符串比较是通过 strcmp 完成的。

替换

if (password == "123")

if (strcmp(password, "123") == 0)

但请注意,strcmp 只能对 NUL 终止的字符串进行操作。

所以你需要这个(我删除了你的评论,所有评论都是我的):

  while (c<=2)
{
while(BusyUSART());

while (!DataRdyUSART());
password[c] = getcUSART();

putrsUSART("\r\n\n You typed: ");
putcUSART(password[c]);

putrsUSART("\r\n\n");
c++;
}

password[c] = 0; // NUL terminated the password

if (strcmp(password, "123") == 0)
{
// password correct
}

关于c - 如何检查以下数组是否包含这些字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49801235/

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