69,373
社区成员
发帖
与我相关
我的任务
分享
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//#include <conio.h>
#define MAX 20
char *g_pData=NULL;
void InsertChar(char data)
{
if(g_pData == NULL)
{
g_pData = (char*)malloc(2);
memset(g_pData, 0, 2);
*(g_pData+0) = data;
}
else
{
int nCurrentLen = strlen(g_pData);
//printf("strlen(g_pData):%d",nCurrentLen);
char* pTemp = (char*)realloc(g_pData,nCurrentLen+2);
if(pTemp != NULL)
g_pData = pTemp;
g_pData[nCurrentLen] = data;
g_pData[nCurrentLen+1] = 0;
}
}
char* FreeInput()
{
char ch;
char szTemp[MAX];
memset(szTemp, 0, sizeof(szTemp));
int nCount=0;
while (1)
{
fflush(stdin);
while (1)
{
ch = getchar();
if (ch=='\n')
{
break;
}
else
{
InsertChar(ch);
}
}
if (g_pData==NULL)
{
free(g_pData);
g_pData=NULL;
printf("您的输入不能为空,请重新输入!\n");
continue;
}
else if(strlen(g_pData) > MAX)
{
free(g_pData);
g_pData=NULL;
printf("您的输入不正确,请重新输入!\n");
continue;
}
else
{
nCount=strlen(g_pData);
for (int i=0; i <nCount; i++)
{
szTemp[i]=g_pData[i];
}
free(g_pData);
g_pData=NULL;
break;
}
}
return szTemp;
}
#include "FreeInput.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#define MAX_LENGTH 32
int main(int argc, char** argv)
{
//接收用户的输入
char *p_UserName=NULL;
char *p_PassWord=NULL;
char *p_Temp=NULL;
//分配空间并且初始化
p_UserName=(char *)malloc(MAX_LENGTH);
p_PassWord=(char *)malloc(MAX_LENGTH);
memset(p_UserName, 0, sizeof(p_UserName));
memset(p_PassWord, 0, sizeof(p_PassWord));
printf(">>请输入用户名:");
p_Temp=FreeInput();
for(int i=0; i <strlen(p_Temp); i++)
{
p_UserName[i]=p_Temp[i];
}
printf(">>请输入密码:");
p_Temp=NULL;
p_Temp=FreeInput();
for(int i=0; i <strlen(p_Temp); i++)// i改成int i 这里改后,输出在20个字符内我的是没有问题。
{
p_PassWord[i]=p_Temp[i];
}
printf("%s", p_UserName);
printf("%s", p_PassWord);
free(p_UserName);
free(p_PassWord);
return 0;
}