代码找不出错误在哪
原题在http://noi.openjudge.cn/ch0107/24/
#include
#include
int main(){
char s[1000][999]={'\0'},ch;
int op=0,oq=0,i,t,e=0;
while(scanf("%c", &ch),ch!='\n')
{
if(ch==' '){
op++;
oq=0;
}
else{
s[op][oq++]=ch;
}
}
for(i=0;i<=op;i++){
if(s[i][0]=='\0') continue;
t=strlen(s[i]);
if(e==0){
printf("%d", t);
e=1;
}
else{printf(",%d", t);}
}
return 0;
}
代码逻辑没有大问题,可能是在一些临界值或者特殊情况的时候处理有问题,比如只有1个单词的时候,单词长度为999,你定义的数组就无法正确的获取字符串的长度,因为没有给\0预留位置。
你先尝试把s[1000][999]改成s[300][1000] ,运行看看是否可以,如果还不行,用我下面的代码试一下,下面的代码修改了一下逻辑,把空字符串全部过滤掉了。
#include <stdio.h>
#include <string.h>
int main(){
char s[300][1000]={'\0'},pre = 0,ch;
int op=0,oq=0,i,t,e=0;
while(scanf("%c", &ch),ch!='\n')
{
if(ch == ' ')
oq = 0;
else
{
if(pre ==' ')
{
op++;
s[op][oq++] = ch;
}else
s[op][oq++] = ch;
}
pre = ch;
}
for(i=0;i<=op;i++){
//if(s[i][0]=='\0') continue;
t=strlen(s[i]);
if(t == 0)
continue;
if(e==0){
printf("%d", t);
e=1;
}
else{printf(",%d", t);}
}
return 0;
}
用scanf("%s"输入字符串就行,每个字符串都是一个单词。
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000] = {0};
int n = 0;
while(scanf("%s",s) != EOF)
{
if(n==0)
printf("%d",strlen(s));
else
printf(",%d",strlen(s));
n++;
if(getchar() == '\n')
break;
}
}