一个简单的 getch() 和 strcmp 问题
我有一个简单的问题,使用函数从用户获取输入,然后检查输入是否“等于”“密码”。然而, 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));
}
I have this simple problem that gets an input from the user using a function then checks if the input is 'equal' to the "password". However, strcmp would never return my desired value, and the culprit is somewhere in my loop that uses getch() to take each character separately and add them to the character array. I found this out by having printf display the character array. If I type in pass word, the function would display it as pass word ". I have no idea on why the closing double quote and a whitespace was included in the array right after the word I typed in. Any idea? Here's the code. Thanks.
#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));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
password
没有有一个终止空字符。
填充超过8个字符
password
c++
应该是ctr++
。
password
does nothave a terminating null char.
stuff more than 8 char into
password
c++
should bectr++
.
您在循环中递增 c 。您应该增加点击率。另外,还有其他人说过的所有内容(空终止符、只有 8 个字符等)。
You're incrementing c in your loop. You should be incrementing ctr. Also, all the stuff everyone else has said (null terminator, only 8 characters, etc).
getch()
是在非标准标头
中定义的函数。当您希望代码可移植时,不建议依赖非标准功能。 :)getch()
is a function defined in a non-standard header<conio.h>
. Relying on non-standard features is not recommended when you want your code to be portable. :)