一些字符串函数的使用
书中的这段代码使用到了strcpy,strcat,strcmp,以及经常用到的strlen
还使用到了sprintf与scanf 中%2d限制读入两个数字,具体代码的含义就且不论
include <stdio.h>
include <string.h>
define MAX_REMINDER 50
define MSG_LEN 60
void read_line(char str[],int n)
{
int i=0;
char ch;
while((ch=getchar())!='\n')
{
if(i<n) str[i++]=ch;
}
str[i]='\0';
}
int main()
{
char reminder[MAX_REMINDER][MSG_LEN+3];
char day_str[3],msg_str[MSG_LEN+1];
int day,i,j,num_reminder=0;
for(;;)
{
if(num_reminder==MAX_REMINDER)
{
printf("NO SPACE LEFT");
break;
}
printf("Enter day and reminder: ");
scanf("%2d",&day);
if(day==0) break;
sprintf(day_str,"%2d",day);
read_line(msg_str,MSG_LEN);
for(i=0;i<num_reminder;i++)
if(strcmp(day_str,reminder[i])<0)
break;
for(j=num_reminder;j>i;j--)
strcpy(reminder[j],reminder[j-1]);
strcpy(reminder[i],day_str);
strcpy(reminder[i],msg_str);
num_reminder++;
}
printf("DAY REMINDER");
for(i=0;i<num_reminder;i++)
{
printf("%s\n",reminder[i]);
}
return 0;
}

浙公网安备 33010602011771号