一个简单的getch()和strcmp问题

ars*_*sus 2 c c++ string getch

我有这个简单的问题,使用函数从用户获取输入,然后检查输入是否与"密码"相等.但是,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));
}
Run Code Online (Sandbox Code Playgroud)

cod*_*ict 6

  • 您的char数组password没有终止null char.
  • 你需要确保不要超过8个字符 password
  • c++应该是ctr++

.

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

password[ctr] = 0;
Run Code Online (Sandbox Code Playgroud)