- 10.2使用函数gets(),从键盘输入一个带有空格的人名,然后把它显示在屏幕上
#include <stdio.h>
#define N 12
int main()
{
char name[N];
printf("Enter your name:");
gets(name);
printf("Hello %s!\n",name);
return 0;
}
字符指针版本
#include <stdio.h>
#define N 12
int main()
{
char name[N];
char *ptr=name;
printf("Enter your name:");
gets(*ptr);
printf("Hello %s!\n",ptr);
return 0;
}
fgets()版本
#include <stdio.h>
#define N 12
int main()
{
char name[N];
char *ptr=name;
printf("Enter your name:");
fgets(ptr,sizeof(ptr),stdin);
printf("Hello %s!\n",ptr);
return 0;
}
- 请编写实现按奥运会参赛国国名在字典中的顺序对其入场次序进行排序。假设参赛国不超150个。
#include <stdio.h>
#include<string.h>
#define N 150
#define MAX_LEN 10
void SortString(char str[][MAX_LEN],int n);
int main()
{
int i,n;
char name[N][MAX_LEN];
printf("How many countries?");
scanf("%d",&n);
getchar();
printf("Input their names :\n");
for(i=0;i<n;i++)
{
gets(name[i]);
}
SortString(name,n);
printf("Sorted results:\n");
for(i=0;i<n;i++)
{
puts(name[i]);
}
return 0;
}
void SortString(char str[][MAX_LEN],int n)
{
int i,j;
char temp[MAX_LEN];
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(str[j],str[i])<0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
}
- MyStrcpy
#include <stdio.h>
void MyStrcpy(char a[],char b[])
{
int i=0;
while(str[i]!='\0')
{
a[i]=b[i];
i++;
}
a[i]='\0';
}
#include <stdio.h>
void MyStrcpy(char *a,char *b)
{
while(*a!='\0')
{
*a=*b;
a++;
b++;
}
*a='\0';
}
- MyStrlen
#include <stdio.h>
unsigned int MyStrlen(const char *a)
{
unsigned int len=0;
for(;*a!='\0';a++)
{
len++;
}
return len;
}
#include <stdio.h>
unsigned int MyStrlen(const char a[])
{
int i;
unsigned int len=0;
for(i=0;a[i]!='\0';i++)
{
len++;
}
return len;
}
#include <stdio.h>
char *MyStrlcat(char *a,char *b)
{
char *p=a;
while(*a!='\0')
{
a++;
}
while(*b!=0)
{
*a=*b;
b++;
a++;
}
*a='\0';
return p;
}