我在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;
} 发布于 2021-07-05 17:14:35
在调用函数之前,您需要提供它的声明,该声明可以出现在例如头部中。
在C中没有标准的函数max,你需要自己写一个这样的函数。
要使用标准函数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[] );发布于 2021-07-05 17:57:17
在你的代码中,max和toupper没有在任何头文件中定义。我想这一定像是bellow。
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define max(a,b) (((a) > (b)) ? (a) : (b))
int la, lb;
int scompare(char [], char []);
int main()
{
char a[50], b[50];
printf("Enter 2 strings \n");
gets(a);
gets(b);
la = strlen(a);
lb = strlen(b);
printf("%d\n", scompare(a, b));
}
int scompare(char a[], char b[])
{
for (int i = 0; i < max(la, lb); i++)
{
int k = a[i] - b[i];
if (k && toupper(a[i]) == toupper(b[i]))
{
return (k > 0 ? 1 : -1);
}
else if (k)
{
return k;
}
}
return 0;
}现在它将成功构建,结果是

但是,我认为你的比较函数效率不高。照我的想法
int scompare(char a[], char b[])
{
for (int i = 0; i < max(la, lb); i++)
{
int k = a[i] - b[i];
if (k == 0) continue;
return k > 0 ? 1 : -1;
}
return 0;
}发布于 2021-07-05 18:01:59
如果使用其他库中的函数,则需要包含以下库:
#include <ctype.h>
...
if(k!=0 &&toupper(a[i])==toupper(b[i]))
return (k>0)?1:-1;
...如果您使用自己的函数,则需要在使用前声明它,并在同一文件中定义它。让我们假设int max(int, int)是您的函数:
#include <stdio.h>
/* function declaration */
int max(int lhs, int rhs);
...
/* usage */
int scompare(char a[la],char b[lb])
{
for(int i=0 ;i<max(la,lb);i++)
{
...
/* definition */
int max(int lhs, int rhs)
{
/* implementation */
}https://stackoverflow.com/questions/68253435
复制相似问题