注册 登录
编程论坛 C++教室

菜鸟.... 不太懂得用字符串

tc121091 发布于 2011-04-23 02:55, 408 次点击
如题, 做题目时出了点问题, 运行程式时会自动停止。

题目要我们找出最大和最小单词, 当用户输入4个字母的单词,程式便停止读入。
例子:
Enter the word: dog
Enter the word: zebra
Enter the word: rabbit
Enter the word: cat
Enter the word: fish

Smallest word: cat
Biggest word: zebra

程序代码:
#include<stdio.h>
#include<string.h>
#define N 100

void main()
{
    char smallest[N]={0L},biggest[N]={0L};
    char input[N];
    int i,length;
    do
    {
        printf("Enter the word: ");
        for (i=0;i<N;i++)
        {
            scanf("%c",&input[i]);
            if (input[i]=='\n')
                break;
        }
        printf("\n\n");
        length=strlen(input);
        if (strcmp(smallest,input)>=0)
            strcpy(smallest,input);
        if (strcmp(biggest,input)<0)
            strcpy(biggest,input);
    }
    while (length!=4);

    printf("\nThe smallest word is %c",smallest);
    printf("\nThe biggest word is %c",biggest);
}

3 回复
#2
qq10235692232011-04-23 07:41
程序代码:
#include<stdio.h>
#include<string.h>
#define N 100

void main()
{
    char smallest[N]={0L},biggest[N]={0L};
    char input[N];
    int i,j=0;
    do
    {
        printf("Enter the word: ");
        for (i=0;i<N;i++)
        {
            scanf("%c",&input[i]);
            if (input[i]=='\r')
                break;
        }
       intput[i]='\0';
        printf("\n\n");
        if (strcmp(smallest,input)>=0)
            strcpy(smallest,input);
        if (strcmp(biggest,input)<0)
            strcpy(biggest,input);
        j++;
    }
    while (j!=4);

    printf("\nThe smallest word is %s",smallest);
    printf("\nThe biggest word is %s",biggest);
}

#3
lucky5635912011-04-23 09:05
字符串是整行输入吗?
#4
Noll_Nie2011-04-23 10:14
使用字符串函数就好了,gets()和puts()可以直接操作字符串
1