Loading...
Select Version
&pagelevel(4)&pagelevel
Definition | #include <string.h> int strncmp(const char *s1, const char *s2, size_t n);
returns 0 (equal), because the first three characters of both arguments match one another. | |
Return val. | < 0 | in the first n characters, s1 is lexically less than s2. |
0 | in the first n characters, s1 and s2 are lexically equal. | |
> 0 | in the first n characters, s1 is lexically greater than s2. | |
Note | Strings terminated with the null byte (\0) are expected as arguments. | |
Example | In the following guessing program, #include <stdio.h>
#include <string.h>
int main(void)
{
int i, n, result;
char s[BUFSIZ], w[BUFSIZ];
printf("Please enter the word to be guessed:\n");
scanf("%s", w);
n = strlen(w);
printf("\nThe word entered has %d letters.\n", n);
i = 0;
do
{
i++;
printf("Your attempt: \n");
scanf("%s", s);
if (strlen(s) > n)
{
printf("Your input is too long!\n");
continue;
}
result = strncmp(s, w, n); /* result is assigned
the result of strncmp */
if (result > 0)
printf("%s is lexically greater.\n", s);
else
{
if (result < 0)
printf("%s is lexically less.\n", s);
}
}
while (result != 0);
printf("Correct! The word was : %s\n", w);
printf("You needed %d attempts.\n", i);
return 0;
}
| |
See also | strcmp | |