如何解决如何解决 Codeforce “A. Way Too Long Words” 问题?
问题: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;
}
我的代码给了我他们想要的答案。但是该网站不批准我的代码。我可能搞错了,但我仍然无法找到问题所在。
请,如果有人发现它,请指给我。
解决方法
根据赋值的描述,接受字符串的字符数组不得少于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++ )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。