• Security incident: ISF was recently accessed by intruders. Please change your password, and change it anywhere else you used it. Read more

I HATE string manipulation in C

I would suggest that you move the logic that decides which destination string to put the result in out of the function and make it a generic function that just modifies the string it is passed in-place.

Something like this:
...

I was going to follow up on my previous post when I had time to point out any further errors, but as jsiv has posted an elegant solution my advice would be to read that and understand it as it epitomises the C approach to coding (I mean that in a good way :) ).
 
Why are you using C strings in a C++ program? Why not use the STL String support?

When I programmed in C++, I used C strings in low-level structures and string objects in user interfaces. This is partly because much of the existing code when I started working there was in C, so I wanted to make the coding style consistent. Also, I liked being able to manipulate strings in the same manner as I did byte arrays from binary data.

Pointer arithmetic was my favorite thing. :)
 
[...] it's fixed. But I don't know why since my change was to fix a different problem in InsertWord.

I'm not sure what you mean here. Did you change RemoveWord at all, or just InsertWord?

The version of RemoveWord that you posted does contain a bug: The only word of a one-word string is the last word of the string, but it is not preceded by a space. The function assumes that it is, backs charpoint up past the beginning of the string, and then writes a '\0' there. Oops.

This works:
Code:
/* Remove the nth word from the string s.  (n is 0-based.)

   Each word contains a single space, as its last character,
   except possibly for the string's last word, which might
   not contain any spaces.

   Example:
   n:  0   1  2 3 45  6
   s: "abc de f g  hi jkl"
*/
void remove(char *s, int n) {
   char *b, *e;  // beginning and one-past-end of word to be removed

   for (b = s; *b && n; ++b)
      if (*b == ' ') --n;

   for (e = b; *e && *e++ != ' ';);

   // when removing last word, remove preceding space too, if any
   if (!*e && s<b && b<e) --b;

   strcpy(b, e);
}
 
I appreciate the thought, but it's fixed. But I don't know why since my change was to fix a different problem in InsertWord. :boggled: Glad to know I'm not the only programmer who finds pointers annoying. I guess there's a reason MacOS was written in PASCAL up through System 7. :eye-poppi

Actually, everything through System 6 was written entirely in assembly language. The new features that were added for System 7 were written in Pascal.
 

ISF - Join now!

Every member here is approved by hand. No bots, no spam, just people who care about evidence and honest debate.

Membership is free!

Create your free account

Back
Top Bottom