为什么这两个程序在VC ++ 2008中提供不同的输出?
毕竟,比较相同的字符串。
#include <stdio.h>
#include <string.h>
main()
{
char targetString[] = "klmnop";
printf ("Compare = %d\n", strcmp(targetString, "abcdef"));
printf ("Compare = %d\n", strcmp(targetString, "abcdefgh"));
printf ("Compare = %d\n", strcmp(targetString, "jlmnop"));
printf ("Compare = %d\n", strcmp(targetString, "klmnop"));
printf ("Compare = %d\n", strcmp(targetString, "klmnoq"));
printf ("Compare = %d\n", strcmp(targetString, "uvwxyz"));
printf ("Compare = %d\n", strcmp(targetString, "xyz"));
}
Compare = 1
Compare = 1
Compare = 1
Compare = 0
Compare = -1
Compare = -1
Compare = -1
#include <stdio.h>
#include <string.h>
main()
{
char targetString[] = "klmnopqrstuvwxyz";
int n = 6;
printf ("Compare = %d\n", strncmp(targetString, "abcdef", n));
printf ("Compare = %d\n", strncmp(targetString, "abcdefgh", n));
printf ("Compare = %d\n", strncmp(targetString, "jlmnop", n));
printf ("Compare = %d\n", strncmp(targetString, "klmnop", n));
printf ("Compare = %d\n", strncmp(targetString, "klmnoq", n));
printf ("Compare = %d\n", strncmp(targetString, "uvwxyz", n));
printf ("Compare = %d\n", strncmp(targetString, "xyz", n));
}
Compare = 10
Compare = 10
Compare = 1
Compare = 0
Compare = -1
Compare = -10
Compare = -13
答案 0 :(得分:3)
零值表示两个字符串相等。 大于零的值表示不匹配的第一个字符在str1中的值大于在str2中的值;小于零的值表示相反。
返回的实际数字(1 / -1或12 / -13)是特定于实现的,可以是任何值。唯一重要的部分是返回0,小于零或大于零。在这方面,他们提供了相同的答案。
答案 1 :(得分:2)
来自strncmp:
返回一个表示字符串之间关系的整数值: 零值表示两个字符串中比较的字符都相等。 大于零的值表示不匹配的第一个字符在str1中的值大于在str2中的值;小于零的值表示相反。
显然strcmp总是为非等号字符返回1或-1,而strncmp返回不等字符之间的差异。由于该行为未定义,因此不存在问题。