C语言:对fgets进行封装

因为fgets在赋值完字符后,在最后会加一个\n换行符,所以为了能够把数组当成字符串,就必须把\n改成\0

代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define username "JacksonWu"
#define password "新年快乐" 


int strlength(char *);
//尝试封装fgets
void getstring(char *, int);


/** 
*验证传入的用户名和密码是否正确
*参数1,:需要验证的用户名
*参数2:需要验证的密码
*返回:如果用户名和密码合法,返回1,否则返回0 
**/


int login(char *, char *);

int main()
{
	char name[20], word[20];
	int len, judge, times, i;	
	//fgets(name, 20, stdin);
	
	for(i = 0; i < 3; i++)
	{	
		printf("请输入用户名:"); 
		getstring(name, 20);
		printf("请输入用户密码:"); 
		getstring(word, 20);
		judge = login(name , word);
		
		if(judge == 1)
		{
			printf("恭喜你,成功登录!\n");
			break;
		}
		else
		{
			printf("您输入的用户名或密码不对!\n"); 
		}
			times = 2 - i;
			printf("您还有%d次机会输入登录信息!\n", times); 
	}
	
	len = strlength(name);
	printf("字符串数组的长度为:%d\n",len);
	return 0;
 } 
 
 
 int login(char *name, char *word)
 {
 	int result = 0;
 	if(strcmp(username , name) == 0 && strcmp(word , password) == 0)
 	{
 		result = 1;
	 }
 	return result;
 }
 
 
 
 
void getstring(char *name, int num)
 {
 	fgets(name, num, stdin);
 	char *find = strchr(name , '\n');//查找函数,查找换行符给指针 
 	if(find)//如果找到了就执行下面的 
 	*find = '\0';//找到了就把\n换成\0 
 }
 
 int strlength(char name[])
 {
 	int count = 0;
 	while(name[count] != '\0')
 	{
 		//当你封装完函数fgets后,里面就把\n替换了,所以这个if可以不要
		/* 
 		if(name[count] == '\n')
 		{
 			name[count] = '\0';
 			break;
		 }
		 */
		 count++;
	 }
 	return count;
 }

posted @ 2022-03-12 23:44  竹等寒  阅读(2)  评论(0编辑  收藏  举报  来源