Click to See Complete Forum and Search --> : can't get second half of && logic to terminate for loop


amozart
March 25th, 2003, 09:35 PM
I have an && condition in my parseWords function below. The first half works. The second half works standing alone without the first portion and without &&. But it won't work in the && condition to terminate my for loop. I am trying to teach myself Visual C++ using Ivor Horton's Visual C++ 6 book. The answer gives an identical logic statement as mine although the program and data structures differ.




//Ex5_5.cpp
//
#include<iostream>
using namespace std;

void parseWords(char array[]);

int main(void)
{
const int MAX = 80;
char string[MAX];

cout << "Enter a string: ";
cin.getline(string,MAX,'\n');

cout << string << endl;


parseWords(string);

return 0;

}

void parseWords(char array[])
{
static int count = 0;
const int MAX=80;
char temp[MAX] = {" "};

for(int i = count; array[i] != ' ' && array[i] != '\0'; i++) // This
same logic statement appears in the textbook's answer section, but it
doesn't work for me
{
temp[i] = array[i];
count++;
cout << i;
cout << temp[i];
}



cout << endl << "testing" <<endl;

count++;
cout << count << endl;

if(array[count] != '\0')

parseWords(array);


}

Kheun
March 25th, 2003, 10:35 PM
I have made changes to your parseWords().

void parseWords(char array[])
{
int count = 0; // No need to use static - Potentially hazardous for multi-threaded application. Also, your code can only call parseWords() once.
const int MAX=80;
char temp[MAX] = {0}; // Make all char in the array equals to 0.

for(int i = 0; array[i] != ' ' && array[i] != '\0'; i++)
{
temp[i] = array[i];
count++;
}

cout << temp << endl;

count++;

if(array[count] != '\0')
parseWords(array+count); // Move the pointer to the newer position so that the function doesn't need count to be static.

}

amozart
March 25th, 2003, 10:56 PM
Thank you - it's a definite improvement.

I haven't tested it yet, but why do you think I am having the problem I am with the second half of the && condition not terminating the for loop?

Kheun
March 25th, 2003, 11:19 PM
Sorry, I didn't test the code with cin.getline() and therefore didn't realize that the for-loop in parseWord() looped beyond the '/0' character.

I have made some changes to parseWord() again.



void parseWords(char array[])
{
int count = 0; // No need to use static - Potentially hazardous for multi-threaded application. Also, your code can only call parseWords() once.
const int MAX=80;
char temp[MAX] = {0}; // Make all char in the array equals to 0.

for(int i = 0; array[i] != ' ' && array[i] != '\0'; i++)
{
temp[i] = array[i];
count++;
}

cout << temp << endl;

// Remove this line so that the next time when parseWord() is called, the array pointer is not pointing beyond '/0'.
// count++;
if(array[count] != '\0')
parseWords(array+count+1); // Move the pointer to the newer position so that the function doesn't need count to be static.

}