【问题标题】:How can I solve Codeforce "A. Way Too Long Words" problem?如何解决 Codeforce “A. Way Too Long Words”问题?
【发布时间】:2021-09-27 01:40:22
【问题描述】:

问题:https://codeforces.com/problemset/problem/71/A

我试过代码:

#include <stdio.h>

int main() {
  int n, lenght;
  char word[99];
  scanf("%d", &n);

  for (int i = 0; i <= n; i++) {
    gets(word);
    lenght = strlen(word);
    if (lenght > 10) {
      printf("%c", word[0]);
      printf("%d", lenght - 2);
      printf("%c\n", word[lenght - 1]);
    } else {
      printf("%s\n", word);
    }
  }
  return 0;
}

我的代码给了我他们想要的答案。但是该网站不批准我的代码。我可能弄错了,但我仍然无法找到问题。

拜托,如果有人能发现它,请指点给我。

【问题讨论】:

  • 一个错误:for(int i=0; i&lt;=n; i++) 应该是for(int i=0; i&lt;n; i++)
  • 另一个错误:要求说“长度为 1 到 100 个字符”。但char word[99]; 最多只能容纳 98 个字符(终止 NUL 需要 1 个字符)。
  • word 太短了
  • @kaylum 但如果我将 word[99] 更改为 word[101],网站会显示“您之前提交过完全相同的代码”

标签: c loops char c-strings


【解决方案1】:

根据赋值的描述,接受字符串的字符数组应不少于100个字符。但是你声明它有 只有 99 个字符

char word[99];

应该这样声明

char word[101];

函数gets 不安全,不受C 标准支持。相反,您至少需要使用标准函数fgets

for循环的条件

for(int i=0; i<=n; i++){

不正确。应该有

for(int i=0; i < n; i++){

scanf这个电话之后

scanf("%d", &n);

输入缓冲区包含换行符'\n'。所以gets 的下一次调用会读取一个空字符串,直到遇到换行符。所以第一个单词被跳过了。

我可以建议例如以下解决方案

#include <stdio.h>

int main(void) 
{
    enum { M = 10, N = 100 };
    
    unsigned int n = 0;
    scanf( "%u ", &n );
    
    while ( n-- )
    {
        char word[N];

        int i = 0;
        
        for ( int c; ( c = getchar() ) != EOF && c != '\n'; i++ )
        {
            word[i] = c;
        }
        
        if ( M < i )
        {
            printf( "%c%d%c\n", word[0], i - 2, word[i - 1] );
        }
        else
        {
            printf( "%.*s\n", i, word );
        }
    }
    
    return 0;
}

如果输入是

4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis

那么输出是

word
l10n
i18n
p43s

程序中更安全的for循环可以如下所示

for ( int c; i < N && ( c = getchar() ) != EOF && c != '\n'; i++ )

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    相关资源
    最近更新 更多