我创建了一个比较字符串的函数,因为我对它总是丢失第二个字符串中的最后一个字符并总是返回“相同的字符串”而感到沮丧,我注意到我在搞乱并使用gets()而不是fgets () 用于第二个字符串。我改变了它,该功能按预期工作。
我的问题是,为什么 gets() 函数减去最后一个字符?它不应该减去空值并保留它吗?
这是否意味着作为 C 的新手,我应该避免使用 gets() 而专注于 fgets()?我开始以与 strcmp() 与 strncmp() 相同的方式来考虑它们
谢谢大家的时间!
注意:我知道最后我真的不需要 (i==j),我只是把它留在那里(也许是额外的安全性?)。
bool compare_string(const char *string1, const char *string2) {
int i = 0, j = 0, result = 0;
while (string1[i] != '\0') {
i++;
}
while (string2[j] != '\0') {
j++;
}
i = 0;
j = 0;
while ((string1[i] != '\0') && (string2[j] != '\0')) {
if (string1[i] < string2[j]) {
result = -1;
break;
} else if (string1[i] > string2[j]) {
result = 1;
break;
} else if (string1[i] == string2[j]) {
result = 0;
}
i++;
j++;
}
if ((result == 0) && (i==j)) {
printf("identical strings \n");
} else if (result == -1) {
printf("not identical, -1 \n");
} else if (result == 1) {
printf("not identical, 1 \n");
}
}
//in main
char str_compare1[STRING_LIMIT];
char str_compare2[STRING_LIMIT];
printf("enter 1st string to compare, (100) characters or less: \n");
fgets(str_compare1, STRING_LIMIT, stdin);
printf("enter 2nd string to compare, (100) characters or less \n");
fgets(str_compare2, STRING_LIMIT, stdin);
result = compare_string(str_compare1, str_compare2);