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

时间:2018-04-12 16:06:50

标签: c arrays

所以我有一个叫做密码的数组。我将数组作为: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结尾,所以我试图在最后添加它,再次没有用。

有没有办法写它以便我不必使用AND门?

感谢您的帮助。

更新的代码:

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;
  }
}

}

1 个答案:

答案 0 :(得分:5)

请注意,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
  }