Reputation: 128
This is the code for removing consecutive words:
std::string unstretch(std::string word)
{
std::string s;
int k=0;
for(int i=0;i<word.length();k++,i++)
{
if(word[i]!=word[i+1])
{
s[k]=word[i];
}
else
k--;
}
s[k]='\0';
return s;
}
This code works if we replace string s
with char s[50]
. Can someone explain why this happens?
Upvotes: 0
Views: 161
Reputation: 1036
The problem is you are treating string as a char array. Its not just a char array. So,
I think what your program does is remove the duplicate characters. This is how you would probably do it:
std::string unstretch(std::string word)
{
std::string s;
for(int i=0;i<word.length();i++)
{
if(word[i]!=word[i+1])
{
s += word[i];
}
}
return s;
}
Upvotes: 0
Reputation: 31488
s
is an empty string. You cannot use operator[]
on an index that doesn't exist.
Upvotes: 3