gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:49:43 25 4
gpt4 key购买 nike

我有一个简单的问题,它使用函数从用户那里获取输入,然后检查输入是否“等于”“密码”。但是,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));
}

最佳答案

  • 您的字符数组 password 没有有一个终止空字符。
  • 你需要确保你没有填充超过 8 个字符密码
  • 另外 c++ 应该是 ctr++

.

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

password[ctr] = 0;

关于c++ - 一个简单的 getch() 和 strcmp 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3784239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com