2

我有一个简单的问题,它使用函数从用户那里获取输入,然后检查输入是否“等于”“密码”。但是,strcmp 永远不会返回我想要的值,罪魁祸首是在我的循环中的某个地方,它使用 getch() 分别获取每个字符并将它们添加到字符数组中。我通过让 printf 显示字符数组发现了这一点。如果我输入密码,该函数会将其显示为密码“。我不知道为什么在我输入的单词之后的数组中包含右双引号和空格。知道吗?这是代码。谢谢。

#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));
}
4

4 回答 4

6
  • 您的 char 数组password没有终止的空字符。
  • 您需要确保您的内容不超过 8 个字符 password
  • c++应该是ctr++

.

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

password[ctr] = 0;
于 2010-09-24T04:46:06.033 回答
2

您在循环中增加 c 。你应该增加 ctr。此外,其他人所说的所有内容(空终止符,只有 8 个字符等)。

于 2010-09-24T04:49:37.943 回答
0

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

于 2010-09-24T04:45:08.097 回答
0
do {
   // stuff char into password.
   ++ctr; 
   } while(c != 13 && ctr < 9);

password[ctr] = '\0';
于 2018-05-02T13:53:21.903 回答