strcmp_kr函数基于K&R的字符串比较功能.
#include<stdio.h>
#include<string.h>
int strcmp_kr (char *s, char *d) {
int i=0;
while ((s[i] == d[i])) {
printf("Entered while loop\n");
if (s[i] == '\0')
return 0;
i++;
}
return s[i] - d[i];
}
int main() {
char s1[15];
char s2[15];
printf("Enter string no. 1:");
scanf("%s", s1);
printf("Enter string no. 2:");
scanf("%s", s2);
strcmp_kr(s1, s2) == 0 ? printf("Strings equal!\n") : \
printf("Strings not equal by %d!\n", strcmp_kr(s1, s2));
Run Code Online (Sandbox Code Playgroud)
}
输出:
$ ./a.out
输入字符串号.1:谦虚
输入字符串号.2:modesy
进入while循环
进入while循环
进入while循环
进入while循环
进入while循环
进入while循环
进入while循环
进入while循环
进入while循环
进入while循环
字符串不等于-5!
问题:为什么while循环输入10次而不是5次?
strcmp_kr(s1, s2) == 0 ? printf("Strings equal!\n") : \
printf("Strings not equal by %d!\n", strcmp_kr(s1, s2));
Run Code Online (Sandbox Code Playgroud)
you have called strcmp_kr(s1, s2) twice ,first in the condition, and second in the printf since your condition is false, so you get 10 times of the print message.
to avoid this, store the return value in a variable like
int rtn = strcmp_kr(s1, s2);
rtn == 0 ? printf("Strings equal!\n") : \
printf("Strings not equal by %d!\n", rtn);
Run Code Online (Sandbox Code Playgroud)