Reputation: 88
I am practicing strings, for the first time, and I am trying to remove consecutive repetitive letters from given words and print it. Say the word is committee, the out put will be comite.
My logic was to compare consecutive letters in the given word and store the letters into another string if they are not same.
When I compile and run my code I get weird symbols. What is the mistake in my code?
#include<stdio.h>
#include<string.h>
int main()
{
char word[20],modword[20];
int i=0,j=0;
gets(word);
for (i=0;i<20;i++)
{
if (word[i]!=word[i++])
{
modword[j]=word[i];
j++;
}
}
puts(modword);
return 0;
}
Upvotes: 1
Views: 132
Reputation: 75062
word[i]!=word[i++]
invokes undefined behavior. It is intuitively explained as because whether of word[i]
and word[i++]
will be evaluated first is not specified and the evaluation order will change which element will be accessed.Try this:
#include<stdio.h>
#include<string.h>
#define MAX_LENGTH 20
int main(void)
{
char word[MAX_LENGTH + 1],modword[MAX_LENGTH], *lf;
int i=0,j=0;
fgets(word, sizeof(word), stdin);
if ((lf = strchr(word, '\n')) != NULL) *lf = '\0';
for (i=0;i<MAX_LENGTH;i++)
{
if (i == 0 || word[i-1]!=word[i])
{
modword[j]=word[i];
if (word[i] == '\0') break;
j++;
}
}
puts(modword);
return 0;
}
Points:
gets()
to avoid buffer overrun.i
in the loop. word[i-1]
won't be evaluated when i == 0
thanks to short-circuit evaluation.Upvotes: 3
Reputation: 28654
You need to apply certain changes, e.g.
char word[20] = {0};
char modword[20] = {0};
int i = 0, j = 0;
fgets(name, sizeof(word), stdin);
for (i=0; i < sizeof(word) - 1;i++)
{
if (word[i] != word[i+1])
{
modword[j] = word[i];
j++;
}
}
Upvotes: 0