我有一个简单的问题,可以使用函数从用户那里获得输入,然后检查输入是否与“密码”“相等”。但是,strcmp永远不会返回我的所需值,罪魁祸首是我的循环中的某个地方,该值使用getch()分别将每个字符添加到字符数组中。我通过让printf显示字符阵列来发现这一点。如果我输入通行字,则该函数将显示为“通行字”。“我不知道为什么在我输入的单词之后的阵列中包含闭合双引号和whitespace。任何想法?这是代码。谢谢。

#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <string.h>

int validateUser();

int main()
{
   for(int x = 0;x<2;x++)
   { 
        if(validateUser())
         {   
             system("cls");
             printf("\n\n\t\t** Welcome **"); break; 
         }
        else                    
         {   
             system("cls");
             printf("\n\n\t\tIntruder Alert!");
             system("cls"); 
         }
   } 


    system("PAUSE>nul");
    return 0;
}

int validateUser()
{
    char password[9];
    char validate[] = "pass word";
    int ctr = 0, c;
    printf("Enter password : "); 
    do
    {
        c = getch();
        if(c == 32)
        {
             printf(" ");
             password[ctr] = c;
        }

        if(c != 13 && c != 8 && c != 32 )
        {
          printf("*");
          password[ctr] = c;
        }
        c++;    
    }while(c != 13);

    return (!strcmp(password, validate));
}
有帮助吗?

解决方案

  • 你的char阵列 password 没有终止的null char。
  • 您需要确保您的塞满8个以上的charpassword
  • c++ 应该 ctr++

.

do {
 // stuff char into password.
 ctr++; 
}while(c != 13 && ctr <8);

password[ctr] = 0;

其他提示

您正在循环中增加C。您应该增加CTR。另外,其他所有人都说的所有内容(无效终结者,只有8个字符等)。

getch() 是在非标准标头中定义的功能 <conio.h>. 。当您希望代码可移植时,不建议依靠非标准功能。 :)

do {
   // stuff char into password.
   ++ctr; 
   } while(c != 13 && ctr < 9);

password[ctr] = '\0';
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top