a****m 发帖数: 693 | 1 #include
#include
#include
using namespace std;
// this function removes trailing spaces from x
void trim (char *str, int size )
{
int i;
/* remove the null terminator */
for ( i = size; i >0; i=i-1 )
{
if ( str[i] == '\n' || str[i]=='\t' || str[i]==' ' )
{
str[i-1] = '\0';
/* we're done, so just exit the function by returning */
return;
}
}
/* if we get all the way to here, there must not have been a
newline! */
}
int main ()
{
char foo[] = "Celtics Rocks ";
int length=strlen(foo);
cout << "x before trim: " << foo <
cout << "the length of foo is: "<< strlen(foo)<
trim (foo, length);
cout << "x after trim :" << foo << endl;
cout << "the length of foo is: "<< strlen(foo)<
system("pause");
return 0;
} |
X****r 发帖数: 3557 | 2 It only erase the last blank.
Change the for loop to:
for (i = size - 1; i >= 0 && (str[i] == '\n' || str[i]=='\t' || str[i]
== ' '); --i);
str[i + 1] = '\0';
【在 a****m 的大作中提到】 : #include : #include : #include : using namespace std; : // this function removes trailing spaces from x : void trim (char *str, int size ) : { : int i; : : /* remove the null terminator */
|
a****m 发帖数: 693 | 3
str[i]
you made the point, the previous only erase one blank.
many thanks
【在 X****r 的大作中提到】 : It only erase the last blank. : Change the for loop to: : for (i = size - 1; i >= 0 && (str[i] == '\n' || str[i]=='\t' || str[i] : == ' '); --i); : str[i + 1] = '\0';
|
g*********s 发帖数: 1782 | 4 if u use a simple test to debug, you can easily find where the bug is.
【在 a****m 的大作中提到】 : #include : #include : #include : using namespace std; : // this function removes trailing spaces from x : void trim (char *str, int size ) : { : int i; : : /* remove the null terminator */
|