初学C++,学习输入输出函数、与C所用库的区别,并初步实现登录操作。操作的主要目的是熟悉C++输入输出函数的用法,以及_getch()是不屏显函数。
源代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<conio.h>
using namespace std;
void Input(char* userName, char* Password);
int Login(char* userName, char* Password, const char* root = "root", const char* pass = "12345") {
if (0 == strcmp(userName, root)) {
if (0 == strcmp(Password, pass)) {
return 1;
}
}
return 0;
}
int main() {
char username[20] = { 0 };
char password[8] = { 0 };
while (1) {
Input(username, password);
if (Login(username, password)) {
cout << "登录成功!\n";
break;
}
else {
cout << "用户名或密码错误,请重新输入\n";
}
}
return 0;
}
void Input(char* userName, char* Password) {
cout << "请输入用户名\n";
cin >> userName;
while (getchar() != '\n');
cout << "请输入您的密码\n";
//cin >> Password; cin为屏显函数,这里用_getch函数(非屏显)
char ch = 0;
int i = 0;
while ((ch = _getch()) != '\r') {
//ch = _getch();
Password[i++] = ch;
putchar('*');
//cout << "输入成功\n";
}
// 这种方式就不行,_getch()需在上面
//while ((ch != '\r')) {
//ch = _getch();
//Password[i++] = ch;
//putchar('*');
cout << "输入成功\n";
//}
Password[i] = '\0';
cout << endl;
//测试
//cout << Password;
}