Hi everyone,
I'm working on a programming assignment for a cs class and I am having trouble figuring out why I am getting an infinite loop in my function flipstring, a function that reverses the order of words in a string while keeping the characters the same. Flipstring calls the function nextword so I will copy both functions. Here is my code,
Code:
int nextword(char *str);
void flipstring(char *str);
int nextword(char *str)
{
static char *s;
static int nextindex;
int thisindex;
// reset the static variables
if (str != NULL) //string is called once. NULL is used to find the nextword in str.
{
s = str;
thisindex = 0;
}
else
{
// set the return value to be the nextindex
thisindex = nextindex;
}
if (nextindex != -1)
{
while((s[nextindex] != ' ') && (s[nextindex] != '\n') && (s[nextindex] != '\t')){
if(s[nextindex]=='\0'){
thisindex=-1;
return thisindex; //returns final index
}
else
nextindex++; //if s is not white space, nextindex is incremented
}
s[nextindex]='\0';
while ((s[nextindex] == ' ') || (s[nextindex] == '\n') || (s[nextindex] == '\t') || (s[nextindex] == '\0'))//nextindex is incremented after \0 is placed
nextindex++;
}
return thisindex;
}
void flipstring(char *str){
int i = nextword(str);
char *c[256];
int j=0,w=0,x=0;
while(i != -1){
c[j]=&(str[i]);
printf("%d: %s\n",j,c[j]); //Here for testing reasons
i = nextword(NULL);
j++;
}
j--; //j was incremented too far in the last while loop
for(j;j>=0;j--){
w=0; //reset w for every string in c
while(c[j][w] != '\0'){
str[x]=c[j][w];
printf("str[x] x=%d c[j][w] j=%d w=%d str=%s",x,j,w,str); //Here for testing reasons
w++;
x++;
}
str[x]=' '; //sets space
x++;
}
str[x]='\n';
str[x+1]='\0';
}
Here is the code I am using to test flipstring,
Code:
void main(int argc, char **argv)
{
char str[] = "Hello Everyone. I'm doing great!";
flipstring(str);
printf("%s",str);
}
I use nextword to save my strings in an array of strings, c. I then try to copy of the characters of the strings in c back to the string str in the reverse order. For some reason my while loop,
Code:
while(c[j][w] != '\0')
, runs infinitely. The print statement tells me that j is decremented down to 1 and stays at 1, while x and w increment infinitely. My only theory as to why the while statement runs forever is that there are no \0 characters in some/all of my strings, but this theory doesn't explain why j is decremented at all in the first place. Any help with this problem would be much appreciated, I have been trying to figure this out for a while now.