permui / ZJUCKC-C-Learning-Assistence

浙江大学竺可桢学院C语言程序设计辅学计划公共仓库。
6 stars 6 forks source link

[practice]#3-卢芳民-洛谷P1308统计单词数 #12

Open Lu-fm opened 4 years ago

Lu-fm commented 4 years ago

P1308 这个题在输入的时候被整了好久.....因为用gets不安全,一开始用scanf%s,最后用getchar吃掉回车,但是运行时却发现输入的时候s[0]和s[1]被跳过了,是从s[2]开始储存字符串.搞不懂所以用了getchar,自己运行没发现什么问题,但是洛谷上Runtime Error,不知道哪里有问题.求教.

#include <stdio.h>
#include <string.h>
void lower(char (*s)[11]);
int main()
{
    char str[100001][11] = {}, tag[11]={};
    int i, j, cnt,index,flag;
    i = j = cnt = index=flag=0;
    while((tag[i]=getchar())!='\n')
    {   
        if(tag[i]>='A'&&tag[i]<='Z')
            tag[i] += 32;
        i++;
    }
    tag[i] = '\0';
    i = 0;
    while(1)
    {
        j = 0;
        while((str[i][j]=getchar())!=' '&&str[i][j]!='\n')
            j++;
        if(str[i][j]=='\n')
        {
            str[i][j] = '\0';
            break;
        }
        else
            str[i][j] = '\0';
        i++;
    }
    lower(str);
    for (j = 0; j <= i; j++)
    {
        if (strcmp(tag, str[j]) == 0)
            cnt++;
        if(cnt)
            flag++;
        if (flag<=1&&j!=0)
            index += strlen(str[j - 1]) + 1;
    }
    if (cnt)
        printf("%d %d", cnt,index);
    else
        printf("-1");
    return 0;
}
void lower(char (*s)[11])
{
    int i = 0,j=0;
        for (;s[i][0]!='\0';i++)
            for (j=0;j<11;j++)
                if(s[i][j]>='A'&&s[i][j]<='Z')
                    s[i][j] += 32;
}
Lu-fm commented 4 years ago

发现了一个问题,数组不够大,可以改成全局变量搞大一点,但是还是过不了......

permui commented 4 years ago

scanf("%s",str) 可以直接读入空格/tab/回车分隔的一个完整的单词,你直接这样读就可以了。 将一行读入 char str[N] 的方法是 scanf("%[^\n]\n",str)。 自己写不太简单的读入是容易错的,一般就是 Runtime Error。把读入改了试试。

lizhiqi-creator commented 4 years ago

这是一个很好的技巧,可以在这里面看看https://blog.csdn.net/sunhaoyn/article/details/41347999

Lu-fm commented 4 years ago

谢谢,学到了~