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.

Recommended Answers

All 3 Replies

No, there's not a function in either the C or C++ library that will do that. You do it manually. First by finding the end of the string and walking back as long as the current character is whitespace, then replace the last occurance of whitespace with '\0'. Then by finding the first non-whitespace character in the string and shifting everything in the string back. You can do the latter with memmove.

Thanks Narue does it have to be replaced with '\0' or is it just a '0'? and would I have to replace all of the whitespace or just the last one for example:

"k,i,m, 0, , , ,0"

Also would it be easier for me beginner to programming not to use memmove as I have no idea how that function works I had a look on google but I didn't understand the examples I found?

>does it have to be replaced with '\0' or is it just a '0'?
'\0' is an escape character with the value of 0 that's used as a string terminator. '0' is not the same thing.

>and would I have to replace all of the whitespace or just the last one
Just the last one. If the string has {'t','e','s','t',' ',' ',' ','\0'} then you only need to replace the first space character after 't' with '\0'. That truncates the string appropriately.

>Also would it be easier for me beginner to programming not to use memmove
The manual solution isn't any simpler:

for ( i = 0; a[i] != '\0'; i++ ) {
  if ( !isspace ( a[i] ) )
    break;
}

if ( i > 0 ) {
  for ( j = 0; a[i] != '\0'; i++, j++ )
    a[j] = a[i];
  a[j] = '\0';
}

Compare that to memmove:

for ( i = 0; a[i] != '\0'; i++ ) {
  if ( !isspace ( a[i] ) )
    break;
}

if ( i > 0 )
  memmove ( a, a + i, strlen ( a + i ) + 1 );
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.