【问题描述】编写自定义函数,函数原型int fun(char *p1,char *p2);,该函数的功能是实现两个字符串的比较。设p1指向字符串str1,p2指向字符串str2。当str1等于str2时,函数返回值为0;当str1不等于str2时,返回两者第一个不相同字符的ASCII码的差值。两个字符串str1和str2由main函数输入,根据fun函数的返回值在main函数中输出不同的结果:
如果fun()函数的返回值等于0,则输出str1和str2相等;
如果fun()函数的返回值大于0,则输出str1大于str2;
如果fun()函数的返回值小于0,则输出str1小于str2;
#include"stdio.h"
#include"string.h"
int fun(char *p1,char *p2);
int main()
{
char str1,str2;
char *p,*q;
int n;
printf("Please enter the first string:");
scanf("%s",str1);
printf("Please enter a second string:");
scanf("%s",str2);
p=&(str1);
q=&(str2);
n=fun(p,q);
if(n==0)
{
printf("str1 is equal to str2");
}
if(n==1)
{
printf("str1 is greater than str2");
}
if(n==-1)
{
printf("str1 is less than str2");
}
return 0;
}
int fun(char *p1,char *p2)
{
int i;
if(strcmp(p1,p2)==0)
{
i=0;
}
if(strcmp(p1,p2)>0)
{
i=1;
}
if(strcmp(p1,p2)<0)
{
i=-1;
}
return i;
}
只能输入str1且结果只有str1 is equal to str2
通过strcmp函数比较字符串的大小
首先,题目的意思就是让你自己实现strcmp函数,不要调用strcmp
输入不了str2是因为变量类型不对,str1实际上也没有正确输入。
要想保存字符串,应该定义char数组来保存,例如char str1[100],str2[100];
后面的p=&(str1);和q=&(str2);去掉&