简体   繁体   中英

Runtime error in codeforces but worked just fine in Dev-C++

I'm trying to solve a problem which requires: a sentence that has less than 150 characters as an input and makes that sentence's characters all to uppercase while removing all extra white spaces, then prints the changed sentence and its number of characters to the screen. For example:
Input: Look in to the abyss
Output: LOOK IN TO THE ABYSS:20
I tested this program on Dev-C++ and it worked just fine but when i submitted it to CodeForces I got runtime error. I hope anyone can help me with this.
( I tried to use scanf("%[^\n]%*c", sen) and fgets(sen, sizeof(sen), stdin) instead of gets(sen) but i still get runtime error. Also, i use a different function strlength instead of strlen since i had another type-related error when submitting that piece of code to CodeForces )
P/s: Sorry for my bad English

#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]) will read out of bounds for i == 0 , which might cause the program to crash if you are lucky. You need to rewrite that function with different logic.

I found the bug !
The error turned out to be at 'void main()' function.
When i replaced it with int main(), i got perfect results in CodeForces.
Thanks everyone for helping me !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM