strcmp问题

strcmp问题,c,C,我需要将用户输入的内容与我以前使用strncpy存储的内容进行比较…我知道strncpy部分工作正常,当我将输入与puser->Username等进行比较时遇到问题 int admin_signIn(struct profile *puser) { int i=0; for(i=0;i<3;i++) { strncpy((puser+i)->UserName, "admin", strlen("admin")+1 ); strncpy((puser+i)->P

我需要将用户输入的内容与我以前使用strncpy存储的内容进行比较…我知道strncpy部分工作正常,当我将输入与puser->Username等进行比较时遇到问题

int admin_signIn(struct profile *puser)
{
 int i=0;


 for(i=0;i<3;i++)
 {
  strncpy((puser+i)->UserName, "admin", strlen("admin")+1 );
  strncpy((puser+i)->Pwd, "password", strlen("password")+1 );

  printf("Enter admin user name:");
  fgets(input,10,stdin);
  rewind(stdin);   
  printf("Enter admin password:");
  fgets(input,10,stdin);

    //printf("the password is %s", puser->Pwd);    
   if(strcmp((puser+i)->UserName, input)==0 && strcmp((puser+i)->Pwd, input)==0)
    {
     printf("The Administrator username and password is incorrect, please try again\n");                                      

    }
   else
    {
     printf("the info is good\n");
    }

  }
   printf("max number of attepmpts exceded, goodbye!");   
}    

除了上面提到的其他问题外,看起来您正在使用一个变量输入来同时保存用户名和密码;这似乎不太可能成功

 printf("Enter admin user name:");
 fgets(input,10,stdin);
 rewind(stdin);   
 printf("Enter admin password:");
 fgets(input,10,stdin);
if(strcmp((puser+i)->UserName, input)==0 && strcmp((puser+i)->Pwd, input)==0)
也试试这个:

而不是:

  strncpy((puser+i)->UserName, "admin", strlen("admin")+1 );
  strncpy((puser+i)->Pwd, "password", strlen("password")+1 );
你可以做:

strcpy((puser + i)->UserName, "admin");
strcpy((puser + i)->Pwd, "password");

然后:

   if(strcmp((puser+i)->UserName, username)==0 && strcmp((puser+i)->Pwd, password)==0)
   {
      /* correct username and password. Do something.. */
   }

现在比较用户键入的用户名和密码。

strcmp在输入匹配时返回0。虽然您正在用输入的密码覆盖输入的用户名…strncpy可能不是您首先要使用的函数。它不是设计用来处理字符串的;它设计用于处理不一定以零结尾的字符数组。确保字符串被终止。puser+i->UserName应该完成什么任务?为什么每次尝试获取用户名/密码时都会使用不同的用户配置文件?目前还不清楚这是您看到的bug的来源,但在任何情况下似乎都没有意义。我不相信你能有意义地将倒带应用于标准输入,这相当于调用fseek,这对标准输入也没有意义。这与你的问题无关,但你使用strncpy的方式完全等同于使用普通的旧strcpy。因此,使用strcpy insterad除了使代码更加清晰之外,不会修复任何问题。但正如pmg所指出的,它显示了一种误解,即为什么以及何时应该使用strncpy,这几乎是不可能的。我曾经将input作为一个全局变量,但现在我将其更改为input 1和input 2,所以基本上我有ifstrcppuser->UserName,input1==0等等。。。但它仍然不起作用…好吧,我明白你关于strncpy@michaelburr的意思…我把它改回strcpy…@jerrycoffin我应该做的是存储管理员和通用管理员密码的密码,我还必须存储5个伪造的用户名和密码,然后让我的程序表现得像有人试图登录一样,如果这样做有意义的话。谢谢你…我把我的程序改成了那样,但你的程序更干净,但我仍然有问题…我想我现在的问题是我的循环。问题不是我的循环,如果我完全去掉fo循环,它仍然不会比较
   if(strcmp((puser+i)->UserName, username)==0 && strcmp((puser+i)->Pwd, password)==0)
   {
      /* correct username and password. Do something.. */
   }