Manil Puri Manil
Manil Puri Manil

Reputation: 117

i am trying to print words from a sentence in c++ but its giving me Segmentation Fault(core dump)

I am trying to print the words from a sentence but it's giving the error:

Segmentation Fault (core dump)

Is it due to the use of gets() function, or is it something else?

void words(char* sentence){
    int len =strlen(sentence);
    for(int i=0;i<len;i++){
        char word[100];
        int j=0;
        while(sentence[i]!='\0' || sentence[i]!=' '){
            word[j++] = sentence[i++];
        }
    word[j] ='\0';
    cout<<word<<endl;
    }
}
int main(){
    char str[100];
    gets(str);    
    words(str);
    return 0;
}

Upvotes: 2

Views: 82

Answers (1)

Rohit
Rohit

Reputation: 152

Your main code itself is not proper. char str[100]; gets(str);

How you will make sure that always input to str will be 100.If input exceed 100 it will cause crash.

Upvotes: 1

Related Questions