密码检查程序

主题: 写一个程序登录时检查用户密码. 用户必须登录时正确的用户名和密码出声. (用户名和密码在程序中定义)

其实, 构建软件时,您会遇到这样的问题很多, 功能齐全的网站 登录. 所以这个问题是非常有用的.

首先,你需要认识到,如果用户输入正确的好吗, 如果用户输入了错误的,他们必须重新输入, 即必须重复多次. 那么有多少次重复? 重复,直到新的权利只 - >事先不知道多少次重复. 所以我们要使用的东西? 使用循环, 意外发生数 ->使用 而HOAC而做.

现在,你还记得while循环的含义,而做:

  • : 虽然一些正确的事情,做一些工作.
  • 而做: 工作,同时东西仍然是正确的.

的 2 这种结构是在词义和用法,所以你可以使用的非常相似. 但仔细观察,我们会看到其中的差别.

代码中使用while循环:

/**
*	Program login, enter username and passwrod until they correct
*/

#include <stdio.h>
#include <string.h>	// for compare string by strcmp

int main() {

	// username and password we have
	char username[] = "nguyenvanquan7826";
	char passwrod[] = "0codauem";

	// username and password user must enter to login
	char user[50], pass[50]; 

	printf("Enter your username: ");
	gets(user);

	printf("Enter your password: ");
	gets(pass);

	while(strcmp(user, username) != 0 || strcmp(pass, passwrod) != 0) {
		printf("\nusername or passwrod incorrect\n");

		printf("Enter your username: ");
		gets(user);

		printf("Enter your password: ");
		gets(pass);
	}

	printf("Login success!\n");

	return 0;
}

在上面的代码,你注意一些要点:
使用库 文件string.h 使用字符串比较函数 STRCMP.
通过用户名和密码字符串我们应该使用 得到 要加入 不应该使用的scanf.
在由前检查条件while循环, 因此,我们必须有一些为它检查, 所以我们之前需要输入用户名和密码. 这会导致我们的代码在使用 while 循环之前重复上面多次. 不过,我们也可以不需要先输入, 因此初始用户和密码字符串将为空.

以下是我们使用 do-while 的代码.

/**
*	Program login, enter username and passwrod until they correct
*/

#include <stdio.h>
#include <string.h>	// for compare string by strcmp

int main() {

	// username and password we have
	char username[] = "nguyenvanquan7826";
	char passwrod[] = "0codauem";

	// username and password user must enter to login
	char user[50], pass[50]; 

	int count = 0; // Counting the number of login times

	do{

		if(count > 0) printf("\nusername or passwrod incorrect\n");

		printf("Enter your username: ");
		gets(user);

		printf("Enter your password: ");
		gets(pass);

		count++;

	}while(strcmp(user, username) != 0 || strcmp(pass, passwrod) != 0);
	
	printf("Login success!\n");

	return 0;
}

在这段代码中, 我们使用count变量来统计登录次数, nếu lần đầu tiên thì không hiện ra là mật khẩu sai, chỉ hiện từ lần thứ 2 trở đi mà thôi.

基本上, bài này khá dễ dàng. Hi vọng các bạn có thể nắm vững 🙂