我有这个简单的问题,从用户使用函数获取输入,然后检查输入是否等于“密码”。然而,strcmp永远不会返回我想要的值,而罪魁祸首是在我的循环中的某处使用getch()分别获取每个字符并将它们添加到字符数组中。通过让printf显示字符数组,我发现了这一点。如果我输入密码,函数会显示为密码“我不知道为什么在我输入的单词后面的数组中包含了结束双引号和空格。任何想法?下面是代码。谢谢。一个简单的getch()和strcmp问题
#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));
}
我看到你已经改变了数组的大小。请您在收到答案后不要这样做。现在我的回答没有意义。 – codaddict 2010-09-24 04:57:29
你也改变了'C++'为'ctr ++',这使得用户@joshD的答案完全无用。请恢复更改。 – codaddict 2010-09-24 05:03:18
对不起,先生,这些只是错别字,但我现在将恢复它。 – arscariosus 2010-09-24 05:08:38