由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - 帮看看这个C++里trim last blanks,错在哪里?
相关主题
相关话题的讨论汇总
话题: foo话题: str话题: trim话题: endl话题: cout
进入Programming版参与讨论
1 (共1页)
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 */

1 (共1页)
进入Programming版参与讨论
相关主题
相关话题的讨论汇总
话题: foo话题: str话题: trim话题: endl话题: cout