C++ Enter键和Backspace键中的getch()异常

C++ Enter键和Backspace键中的getch()异常,c++,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')

我想使用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;
}
#包括
#包括
使用名称空间std;
int main()
{
charpasswd[20];
char ch='x';
cout怎么样

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
inti;
对于(i=0;i<20;)
{
int ch=getch();
如果(ch='\b')
i=std::max(0,i-1);//退格,返回一个字符
else if(ch='\r')
continue;//继续循环不需要的特殊字符
else if(ch='\n')
break;//在换行符处结束循环
其他的
passwd[i++]=ch;//向字符串添加字符
}
passwd[i]='\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++;
    }
}
while(ch!='\n')
{
ch=getch();
如果(ch!='\n'&&ch!='\r')
{
passwd[i]=ch;
不能检查这个

#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;
}
#包括
int main(){
字符str[100],c='';
int i=0;
printf(“\n输入密码[最大长度10]:”;

while(我用简单的
if
语句检查他们?谢谢,但我在提问之前检查了。它不起作用。可能是,windows中也会返回\r。顺便说一下:把c风格io(
getch
)和c++风格io(
coud
)混在一起不是一个好主意,尤其是在涉及缓冲区的情况下(在您的代码中,
cout
-输出甚至没有刷新。“我在提问之前检查过。它不起作用”-也许这就是您的问题应该涉及的内容。