请编写一个函数int compare(char *s,char *t)), 该函数的功能是对两个字符串进行比较。当s所指字符串和t所指字符串相等时,返回值为0;当s所指字符串大于是t指字符串时,返回值大于0;当s所指字符串小于t所指字符串时,返回值小于0。 注意:部分源程序已存在文件PROC8.cpp中。 文件PROC8.cpp的内容如下: //PROC8.cpp #include <iostream> #include <string> using namespace std; int compare(char *s,char *t) {//* * * * * * * * * } int main () { char str1[100],str2[100]; int result; cout<<"Input the first string\n"; cin>>str1; cout<<"Input the second string\n"; cin>>str2; result=compare(str1,str2); if (result==0) cout<<"string1=string2 ! \n"; else if (result>0) cout<<"string1>string2 ! \n"; else cout<<"string1<string2 ! \n"; return 0; }
参考答案:
解析:函数compare()的定义如下: int compare(char *s,char t) { while(*s && *t&& *s==*t) { s++; t++; } return (*s-*t); } 函数的功能是对两个字符串进行比较。当s所指字符串和t所指字符串相等时,返回值为0:当s所指字符串大于t所指字符串时,返回值大于0:当s所指字符串小于t所指字符串时,返回值小于0。