I don't understand why it stops right after it reaches the line " if(strcmp(next,str2) == 0) return; "
for now I commented out the %.*s print line just so I can fully print the two strings that are being compared before it reaches the if statement so the 5 is irrelevant in my example input.
when I print the two strings "next" and "str2", the following shows
I can see the string "ABC DEF" is not the same as "BC DEFA" but it seems it satisfies the if statement because it stops the marquee function. When I comment out the if statement, it'll go through infinite recursion.
Maybe it is same I thought so I printed the strcmp program of the two strings
It shows strcmp is -1, which isn't 0
Can someone enlighten me? Maybe I am just missing something simple or is there a better way to break out of my recursion once next is equal to str2.
edit: I put in the rotate function
int main(){
int n,i,signlength;
char sign[100]; //max 99 letters
//get number of cases
scanf("%d",&n);
//process each case
for(i=0;i<n;i++){
//ignore rest of line \n
char ic;
while ( (ic = getc(stdin)) != EOF && ic != '\n');
//take in sign string and length of sign
gets(sign);
scanf("%d",&signlength);
if(signlength >= strlen(sign))
printf("[%-*s]\n",signlength,sign);
if(signlength < strlen(sign)){
printf("%s\n",sign);
//printf("[%.*s]\n",signlength,sign);
marquee(sign,signlength,sign);
}
}
return 0;
}
char* marquee(char* str, int size, char* str2){
char* next = rotate(str);
printf("%s\n",next);
//printf("[%.*s]\n",size,next);
if(strcmp(next,str2) == 0)
return;
return marquee(next,size,str2);
}
void swap(char* a, char* b){
char temp = *a;
*a = *b;
*b = temp;
}
void reverse(char* array, int size){
int i;
for(i=0;i<size/2;i++)
swap(array + i, array + (size-i-1));
}
char* rotate(char* str){
reverse(str +1, strlen(str) -1);
reverse(str, strlen(str));
return str;
}
Your rotate and reverse functions both operate on your character array in-place. In fact, if you look at rotate
, you can see it always returns str
. So when you do:
char* next = rotate(str);
All it's doing it rotating str
in-place and then returning str
. After the call, next
has the same value as str
, and the original contents of str
are no longer available.
If you want to preserve str
, just make a copy of it. For instance, you could do:
char* next = rotate(strdup(str));
That will first copy str
, then call rotate
which will destructively modify the copy, leaving str
unchanged.