bbluthang wrote:
> Hi i'm trying to write some functions for a version of Eliza and can't
> seem to find way to reduce multiple instances of whitespace to a
> single instance -
>
> while((line[i] != '\0') || (line[i] != '.'))
> {
> /*This statement checks for two or more spaces together,
> by comparing the current character with the previous one.
> If found, i is incremented, thereby skipping the multiple spaces.
> The result is then copied into 'cleaned'. */
>
> if((line[i] == ' ' && line[i-1] == ' '))
> {
> i = i + 1;
> }
> cleaned[j] = line[i];
> j = j + 1;
> i = i + 1;
> }
> /*The 'cleaned' array, all lowercase and single spacing, is
> copied
> back into 'line' */
> strcpy(line, cleaned);
> }
>
> I also tried -
>
> if((line[i] == ' ' && line[i-1] == ' '))
> {
> i = i + 1;
> }
> line[j] = line[i];
> j = j + 1;
> i = i + 1;
> }
>
> both ways give me a 'segmentation error' when i try to run the program.
> I'd really appreciate a nudge to point me in the right direction
> thanks
> Andrew
Your problem consists of three out-of-bounds problems. The 'line[i-1]'
is one problem area. Think: What happens when i = 0 and the string
starts with a space? The strcpy() is the other problem area. The while
loop stops at the '\0' and you don't add one to 'cleaned'. The last
problem is:
while ((line[i] != '\0') || (line[i] != '.'))
Think that one through really carefully. Hint: Infinite loop.
The approach you use is somewhat faulty. Think what happens if three
spaces are together? You end up with two spaces in the result. The
correct way to handle this is to use a variable to track the last
character (which, BTW, fixes one of the out-of-bounds problems at the
same time because you initialize it before the while loop to a non-space
value).
if (line[i] != ' ' || LastChr != ' ')
{
cleaned[j] = line[i];
j++;
}
LastChr = line[i];
i++;
--
Thomas Hruska
CubicleSoft President
Ph: 517-803-4197
*NEW* MyTaskFocus 1.1
Get on task. Stay on task.
http://www.CubicleSoft.com/MyTaskFocus/