Truncating spaces off of the end of C++ style strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mohaakilla51
    New Member
    • Jul 2007
    • 39

    Truncating spaces off of the end of C++ style strings

    OK, so I have a function that deals with strings, fixing them so that I can handle them easier. Here is the function:
    Code:
    string fix(string str)
    {
           int length = str.size();
           for (int i = 0; i < length; ++i)
           {
               str[i] = tolower(str[i]);
           }
           
           for (int i = length; str[i] == " " || str[i]==0; --i)
           {
               str.erase(i);
           }
           return str;
    }
    the problem is, that it doesn't like the part where I truncate off the whitespace (or at least I try to, the method I am using is probably crap), it wont compile the second for loop, because
    Originally posted by Dev-C++
    ISO C++ forbids comparison between pointer and integer
    BTW, I am using Dev-C++ if that has anything to do with it.

    So my question is, how would I do this? The reason I have to truncate the spaces is I am using getline, and have functions later on that count the length of the string...
    Last edited by mohaakilla51; Oct 18 '07, 03:22 AM. Reason: fixed quote/typos
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    While the last character is a ' ' (space) character, use the .substr() method to get the portion before the last character.

    It's not efficient at all, but it's what I use.

    Comment

    • mohaakilla51
      New Member
      • Jul 2007
      • 39

      #3
      yeah, but how would I do that?
      [code=c]
      while(str[str.length()-1]==' ')
      {
      str = str.substr(0,st r.length()-1);
      }
      [/code]
      it tells me I cannot do that, but will let me do this:
      [code=c]
      while(str.subst r(str.length()-1,1)==' ')
      {
      str = str.substr(0,st r.length()-1);
      }
      [/code]
      Can anyone tell me why?

      But my original question has been answered, thank you.

      Comment

      Working...