Hey guys I was just wondering is there a c++ function that will eliminate white space from the start and end of a character array data obtained with the getline function? Thanks.

02-18-2006

7stud

No....

02-18-2006

dwks

You could write your own functions to do both of those things.

The eliminate-trailing-whitespace is easier -- just start from the end of the string, work backwards until you find a non-whitespace character, add one, and make that the new end of the string. Something like this:

The remove-leading-whitespace is a bit trickier. You'd have to start at the beginning of the string, find the first non-whitespace character, and move the rest of the string, starting with that character, to the beginning.

02-18-2006

182

Thanks for the reply but I am quite new to C++ so I don't think I will be able to do it that way as I don't fully understand the code.

02-18-2006

dwks

What part don't you understand? size_t?

02-18-2006

182

size_t and isspace and to be honest I wouldn't be able to create the code for whitespace at the start of the array.

02-18-2006

dwks

Well, you could use intand casts and if(x==' '||x=='\n'||...), but size_t and isspace() are easier. :)

02-18-2006

SlyMaelstrom

A nice simple solution is reading in the beginning with a regular extraction eliminating the beginning whitespace, reading in the rest with a getline using a space delimeter, then strcpy() the two.

02-18-2006

dwks

Try something like this:

Code:

size_t x = 0;
while(isspace(s[x++]));
memmove(s, s+x, strlen(s)+1-x);

I think that will work but you'd better test it. :)

02-18-2006

182

Hey sly what do u mean by a regular extraction.

02-18-2006

182

Quote:

Originally Posted by dwks

Try something like this:

Code:

size_t x = 0;
while(isspace(s[x++]));
memmove(s, s+x, strlen(s)+1-x);

I think that will work but you'd better test it. :)

Hey thanks what does the memmove do?

02-18-2006

dwks

Sly's using an extra buffer, which is inefficent and unnessesary. memove() is better (it handles overlaps).

Sly's using an extra buffer, which is inefficent and unnessesary. memove() is better (it handles overlaps).

I'm not the king of efficiency, at my point in my programming knowledge, so I'm not sure, but between your two functions of removing beginning and end whitespace, you have how many calls to isspace() and strlen()? I don't know how long one call takes or one execution of reading from a buffer takes, but I'd be willing to bet that one cin and one cin.getline() gets to be quicker after about (random guess) 10 spaces of whitespace. I don't know. Maybe not. If you know, then please enlighten me on some details.