Friday, July 31, 2009

Trimming whitespace in C++?

I'm in an introductory course to C++, and I'm almost done writing a program. I'm having problems with one function though. It's supposed to trim all whitespace (not just that at the beginning and end--all spaces and tabs). This is what I have:





char* str_trim(char* str)


{


char* trim;





for(str; *str != '\0'; str++)


{


if(*str != ' ' %26amp;%26amp; *str != '\t')


{


trim = str;


trim++;


}


}





strcat(trim, '\0');


str = trim;





return str;


}





The program compiles, but this function (fine without it) is causing a Windows error message requires the command prompt to close. I've been over and over it, but I cannot figure out what is wrong. I would be grateful for any input. Thanks!

Trimming whitespace in C++?
Many ways to do this, but I'll use your code as a foundation





char* str_trim(char* str)


{


char* trim=str;





while(*trim)


{


if(*trim == ' ' || *trim == '\t') {


strcpy(trim,trim+1);


} else {


trim++;


}


}





return str;


}
Reply:kathryn,





Glad to see it. I didn't mean to give you a hard time, but it seems like many people get answers and forget to select a best answer. BTW, something has been weird with Yahoo lately. That might explain the delay. Report It

Reply:Hey dude





i have tried to create a prog it works what u r trying to do with urs.





#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;string.h%26gt;


#define max 100


void str_trim(char* str){


char trim[max];


int i;


for(str,i=0; *str != '\0'; str++){


if(*str != ' '){


trim[i] = *str;


i++;


}


}


puts(trim);


}





void main(){


clrscr();


char c[max];


gets(c);


str_trim(c);


getch();


}





check this prog and let me know if this works....ok





and one more thing man


in your prog one problem that i have seen is





in trim = str;


this line actually equals the whole string what we have enterd


in str to trim so.


pointer stroes address so if u will equate one pointer to other as a = b it will stores the to which b is pointing in a.





so it will not work to do ur task u have to work on values.


ok





i think it will work





bye..
Reply:kathryn,





If you appreciate Duane's answer, you might want to select his as the best answer to give him proper credit (and points). ;-)
Reply:looks okay. I dont see any problem.

flower pots

No comments:

Post a Comment