我正在测试一个小程序,它基本上比较了2个输入字符串是否相同(如strcmp所做)。然而,我不断得到结果说2串不管是什么。如果有人能发现一些错误,我会感激
int comp(char str1[], char str2[]) {
int i = 0;
while (str1[i] == str2[i]) {
if (str1[i] == '\0' || str2[i] == '\0')
break;
i++;
}
if (str1[i] == '\0' && str2[i] == '\0')
return 0;
else
return -1;
}
int main(int argc, char * * argv) {
int cmp;
char str1[1000], str2[1000];
cmp = comp(str1, str2);
if (cmp == 0)
printf("The two strings are identical.\n");
else
printf("The two strings are different.\n");
return 0;
}
答案 0 :(得分:8)
你的职能works just fine。唯一的问题是你的两个字符数组没有初始化,导致未定义的行为。
答案 1 :(得分:0)
这是一个使用命令行参数的实现。
#include <stdio.h>
#include <stdlib.h>
int comp(char str1[], char str2[])
{
int i = 0;
while (str1[i] == str2[i])
{
if (str1[i] == '\0' || str2[i] == '\0')
break;
i++;
}
if (str1[i] == '\0' && str2[i] == '\0')
return 0;
else
return -1;
}
int main(int argc, char * * argv)
{
if( 3 != argc )
{
printf( "USAGE: %s, firstString secondString\n", argv[0]);
exit(EXIT_FAILURE);
}
// implied else, correct number of parameters
if ( !comp( argv[1], argv[2]) )
printf("The two strings are identical.\n");
else
printf("The two strings are different.\n");
return 0;
}