的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));
}
輸出比較功能:
$。 /a.out
輸入字符串編號。 1:謙虛
輸入字符串編號。 2:modesy
已輸入而輸入的循環
while循環
進入while循環
進入while循環
進入while循環
進入while循環
進入而循環
進入while循環
進入while循環
進入while循環
字符串不等於-5!
問題: 爲什麼while循環輸入10次而不是5次?
不要使用'scanf()'而不指定字段寬度,否則它有緩衝區溢出的風險,但它並不完全關係到你的問題。我提到它是一種預防措施:) – 0decimal0