我正在 c 中创建 strcmp() 的用户定义函数。
#include <stdio.h>
#include <string.h>
int la,lb; // la and lb for length of 2 strings
int scompare(char [],char []);
int main() {
char a[50],b[50]; // a and b are 2 strings
printf("Enter 2 strings \n");
gets(a);
gets(b);
la =strlen(a);
lb =strlen(b);
printf("%d",scompare(a,b));
}
int scompare(char a[la],char b[lb])
{
for(int i=0 ;i<max(la,lb);i++)
{ // loop for comparing characters of 2 strings
// here in vs code it is showing error --->
// warning: implicit declaration of function 'max' [-Wimplicit-function-declaration]
for(int i=0 ;i<max(la,lb);i++)
int k = a[i]-b[i];// k is the sum of ascii of characters of a and b
if(k!=0 &&toupper(a[i])==toupper(b[i]))
return (k>0)?1:-1;
// other error is showing here in function toupper ---> warning: implicit declaration of function 'toupper' [-Wimplicit-function-declaration]
if(k!=0 &&toupper(a[i])==toupper(b[i]))
else if(k!=0)
return k;
}
return 0;
}
在调用函数之前,您需要提供它的声明,该声明可以出现在例如标题中。
max
C 中没有标准函数,你需要自己编写这样的函数。
要使用标准功能,toupper
您需要包含标题<ctype.h>
#include <ctype.h>
这个循环(如果假设函数max
是在某处定义的)
for(int i=0 ;i<max(la,lb);i++)
可以调用未定义的行为,则字符串的长度彼此不相等。
注意该函数gets
不是标准的 C 函数。这是不安全的。你应该使用fgets
.
而这个函数声明
int scompare(char a[la],char b[lb]);
没有意义。
该函数应声明为
int scompare( const char a[], const char b[] );
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句