[英]Runtime error in codeforces but worked just fine in Dev-C++
我正在尝试解决一个问题,该问题需要:输入少于 150 个字符的句子,并将该句子的字符全部变为大写,同时删除所有额外的空格,然后将更改后的句子及其字符数打印到屏幕上. 例如:
输入: Look in to the abyss
Output:观察深渊LOOK IN TO THE ABYSS:20
我在 Dev-C++ 上测试了这个程序,它运行得很好,但是当我将它提交给 CodeForces 时,我得到了运行时错误。 我希望任何人都可以帮助我。
(我尝试使用 scanf("%[^\n]%*c", sen) 和 fgets(sen, sizeof(sen), stdin) 而不是 gets(sen) 但我仍然遇到运行时错误。另外,我使用一个不同的 function strlength 而不是 strlen 因为我在将该段代码提交给 CodeForces 时遇到了另一个与类型相关的错误)
P/s: 对不起我的英语不好
#include <ctype.h>
#include <stdio.h>
int strlength(char* str){
int i,j = 0;
for (i=0; str[i]!= '\0';i++)
++j;
return j;
}
void strip_white_spaces(char* str){
int x,i;
for (x=i=0; str[i]!='\0';i++){
if (!isspace(str[i])||((i>0) && (!isspace(str[i-1]))))
str[x++] = str[i];
}
if (isspace(str[x-1]))
str[x-1]='\0';
else str[x] ='\0';
}
void touppercase(char* str){
int i;
for (i = 0; str[i] != '\0';i++ ){
if (str[i] >= 'a' && str[i] <= 'z')
str[i] -= 32;
}
}
void main(){
char sen[150];
gets(sen);
strip_white_spaces(sen);
touppercase(sen);
int s = strlength(sen);
printf("%s:%d", sen, s);
}
isspace(str[i-1])
将超出i == 0
的范围,如果幸运的话,这可能会导致程序崩溃。 您需要用不同的逻辑重写 function 。
我发现了错误!
错误原来是在'void main()' function。
当我用 int main() 替换它时,我在 CodeForces 中得到了完美的结果。
谢谢大家帮助我!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.