strcmp()函数比较两个字符串的大小

//比较两个从键盘输入的字符串
#define _stdc_want_lib_ext1_ 1
#include
#include

#define max_length 21
int main(void)
{
	char word1[max_length];
	char word2[max_length];
	int retval;	//C语言的数据定义和数据操作是分开的,数据定义就定义,定义过后再操作
	printf("type in the first word (maximum %d characters):",max_length - 1);	//因为字符数组结束符'\0'占有一个位置, 所以可输入的字符长度为字符长度减1
	retval = scanf_s("%s",word1,sizeof(word1));
	if(EOF == retval)	//scanf_s函数返回一个整数值,如果超出了字符数限制,就返回符号EOF的值
	{
		printf("error reading the word.\n");
		return 1;
	}

	printf("type in the second word (maximum %d characters):",max_length - 1);
	retval = scanf_s("%s",word2,sizeof(word2));
	if(EOF == retval)
	{
		printf("error reading the word.\n");
		return 2;
	}

	if(strcmp(word1,word2) == 0)	//先判断输入的两个字符串是否相等
		printf("you have entered identical words");
	else
		printf("%s precedes %s\n",
			(strcmp(word1,word2) < 0) ? word1 : word2,	//从第一个位置开始比较,若对应位置word1

结果截图:



你可能感兴趣的:(C)