我正在编写一个程序,根据K.N.King问题中的字典顺序找到最小和最大的单词。找到一个单词中最大和最小的单词,直到用户输入一个4个字母的单词。
首先,我使用strcmp来比较输入字与最大或最小。然后使用strcpy将输入字符串复制到最大或最小。
#include <string.h>
#include <stdio.h>
main()
{
char inputStr[20] ;
char max[20];
char min[20];
int length =0;
do
{
printf("pls, input your string: ");
gets(inputStr);
if(strcmp(inputStr,max) > 0)
strcpy(max,inputStr);
if (strcmp(inputStr,min) < 0)
strcpy(min,inputStr);
length = strlen(inputStr);
}
while (length != 4);
printf("largest word is: %s\n",max);
printf("smallest word is: %s",min);
}
例如。
Enter Word : Cat
Enter Word : Dog
Enter Word : penguin
Enter Word : bear
the smallest word is bear
the largest word is penguin
但是,在运行程序时,最大的单词始终是特殊字符,最小的单词始终是正确的。我的程序显示了结果
the largest word is:
the smallest word is: bear
修订
#include <stdio.h>
#include <string.h>
#define N 20
int main( void )
{
char max[N];
char min[N];
char (*ch)[N];
char inputStr[N] ;
int length = 0;
fgets(inputStr, sizeof(inputStr), stdin);
// Technique from https://stackoverflow.com/a/28462221/701302
inputStr[strcspn(inputStr, "\n")] = 0;
// Set both max and min to initial input in order to ...
strcpy(max,inputStr);
strcpy(min,inputStr);
do
{
fgets(inputStr, sizeof(inputStr), stdin);
inputStr[strcspn(inputStr, "\n")] = 0;
// ... now have basis for valid comparison
if (strcmp(inputStr,max) > 0){
strcpy(max,inputStr);
}
else
if ( strcmp(inputStr,min) < 0){
strcpy(min,inputStr);
}
length = strlen(inputStr);
} while (length != 4);
printf("largest word is: %s\n",max);
ch = &min;
if (strcmp(ch,"") == 0){
ch = "[empty string]";
}
printf("smallest word is: %s",ch);
}
注意:使用fgets()比使用gets()更安全。 get()危险的原因是每个article潜在缓冲区溢出的b / c。但是,使用fgets(),输入可能会以换行符结束,因此您需要删除它。尽管你可能会使用strtok(),但它的设计并没有考虑到这种可能性,因为chux评论说,如果用户的输入包含换行符,则不够。
我从here那里得到了一个提示,我再次修改了这个答案。该技术使用strcspn(),它返回str1中字符数而不是str2中的字符数。因此,每当输入包含一个或多个可打印字符或换行符时,换行符都会被替换。因此,我在ideaone.com上修改了代码和输入。所以,现在输出反映最大的单词是企鹅,最小的单词是空字符串。但是,如果你仅使用OP的original input来运行代码,那么结果将是企鹅并且分别作为词典上最大和最小的单词。