Enter和Backspace键中的getch()异常

时间:2014-01-09 10:28:00

标签: c++

我希望使用getch()方法获取除Enter和Backspace之外的一些字符。

我的代码:

#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
    char passwd[20];
    char ch = 'x';
    cout << "Enter Password: ";
    int i = 0;

    while(ch != '\n') 
    {
        ch = getch();
        passwd[i] = ch;
        cout << (char)254; // write dots instead of password that user entered
        i++;
    }
    passwd[i] = NULL;
    return 0;
}

我的代码获得了Enter和Backspace,但我不想要那些。我确实为这两个密钥做了例外。

我想编写一个代码来从用户那里获取密码并编写*代替它们。

我正在使用C ++。NET Console应用程序。

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

怎么样

int i;
for (i = 0; i < 20; )
{
    int ch = getch();
    if (ch == '\b')
        i = std::max(0, i - 1);  // Backspace, go back a character
    else if (ch == '\r')
        continue;  // Continue loop for unwanted special characters
    else if (ch == '\n')
        break;  // End loop at newline
    else
        passwd[i++] = ch;  // Add character to string
}
passwd[i] = '\0';  // Terminate string

答案 1 :(得分:0)

你可以这样做

while(ch != '\n') 
{
    ch = getch();
    if(ch !='\n' && ch!='\r')
    {
        passwd[i] = ch;
        cout << (char)254; // write dots instead of password that user entered
        i++;
    }
}

答案 2 :(得分:0)

检查

#include<stdio.h>
int main(){
char str[100],c=' ';
int i=0;
printf("\n Enter the password [max length 10] : ");
while (i<=100){
    str[i]=getch();
    c=str[i];
    if(c==13) break;
    else if(c=='\b') printf("\b \b");
    else printf("*");
    i++;
}
str[i]='\0';
i=0;
printf("\n");
printf("\n Your password is : %s",str);
return 0;
}