【发布时间】:2018-03-16 20:19:08
【问题描述】:
我正在尝试制作一个 C++ 程序,该程序接受用户的用户名和密码,并将其与已存储在变量中的用户名和密码相匹配。对于密码,出于隐私考虑,我使用 *(星号)字符而不是实际字符来显示。
#include <iostream.h>
#include <conio.h>
#include <dos.h>
#include <string.h>
void main(void) {
clrscr();
gotoxy(10,10);
cout << "Username: ";
gotoxy(10,12);
cout << "Password: ";
char name1[10] = {"Apple"};
char name2[10];
char pass1[10] = {"Orange"};
char pass2[10] = {""};
gotoxy(23,10);
cin >> name2;
gotoxy(23,12);
cout << pass2;
int i = 0;
char ch;
while ((ch = getch()) != '\r') {
putch('*');
pass2[i] = ch;
i++;
}
if (strcmp(name1, name2) == 0 && strcmp(pass1, pass2) == 0) {
clrscr();
gotoxy(40,10);
cout << "YES!!!";
} else {
clrscr();
gotoxy(40,10);
cout << "NO!!!";
}
}
问题是当我尝试使用键盘上的退格键时,我没有删除字符,而是在其末尾添加了更多字符。我可以通过导入 C 语言的 string.h 库来使其工作。但是有什么方法可以通过使用代码中已经定义的库来使其工作,而不必使用 string.h 库。
【问题讨论】:
-
退格是一个字符...相应地处理它
-
在你的 while 循环中处理它:
if (ch == '\010' && i) { cout << "\010 \010"; --i; } else { ...existing stuff for other chars... } -
顺便说一句,您可以将退格称为 '\b'。
标签: c++