【问题标题】:a simple getch() and strcmp problem一个简单的 getch() 和 strcmp 问题
【发布时间】:2010-09-24 04:43:55
【问题描述】:

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

【问题讨论】:

  • 我看到你改变了数组大小。收到答复后请不要这样做。现在我的回答没有意义。
  • 您还将c++ 更改为ctr++ 这使得用户@joshD 的回答完全没用。请还原更改。
  • 抱歉先生,这些只是错别字,但我现在要恢复它。

标签: c++ c string getch


【解决方案1】:
  • 您的字符数组password 没有 有一个终止空字符。
  • 您需要确保您没有 将超过 8 个字符的内容放入 password
  • 同样c++ 应该是ctr++

.

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

password[ctr] = 0;

【讨论】:

  • 哦,所以我必须在用户按下回车后立即显式添加 /0 吗?
  • 其实是\0,其值为0,所以你可以赋值0
  • 非常感谢先生。现在我已经完全明白了。我以为编译器会自动输入 0,但现在我知道不是。此外,我已恢复更改。对不起,先生。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 我知道先生,但是这些信息对我有什么帮助?
    • 它可能会提示您寻找替代方案,无论是来自&lt;stdio.h&gt; 的 C 风格,还是使用 std::cin 的成员函数的 C++ 风格。类似地,'\n' 是换行符的可移植表示法,是硬编码 ASCII 13(回车代码,很少用于 DOS/Windows 之外)的一个很好的替代方法。不过,当您刚开始学习编码时,这不是优先事项。
    【解决方案4】:
    do {
       // stuff char into password.
       ++ctr; 
       } while(c != 13 && ctr < 9);
    
    password[ctr] = '\0';
    

    【讨论】:

    • 如果您能解释一下为什么您的解决方案有效而 OP 的解决方案无效,那就更好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多