LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 614|回复: 2

编译器的差异 or os的差异 or 程序的问题?

[复制链接]
发表于 2005-8-26 17:32:39 | 显示全部楼层 |阅读模式
大家帮我看看。
////////////file mystring.h
#ifndef MYSTRING_H
#define MYSTRING_H
#include<string>
using namespace std;
class MyString :public string
{
public:

        MyString(void):string(){};
        MyString(const char* str):string(str){};
        MyString(const string& basd):string(basd){};
        //Returns a MyString that has whitespace removed from the start and the end
        MyString stripWhiteSpace( ) const;
        /*
                Returns a string that has whitespace removed from the start and the end,
        and which has each sequence of internal whitespace replaced with a single space.
        */
        MyString simplefyWhiteSpace(void) const;

};

#endif //MYSTRING_H

////////////file mystring.cpp
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

#include "mystring.h"
MyString MyString::stripWhiteSpace( ) const
{
        string::size_type begin,end,len=length();
        string strTemp = substr(0, len);
        begin =0;
        while(begin<=len)
        {
                if ( isspace(strTemp[begin]) ) begin++;
                else break;
        }
        end = len - 1;
        while(end>=0)
        {
                if(isspace(strTemp[end])) end--;
                else break;
        }
        return substr(begin,end - begin+1);
}

MyString MyString::simplefyWhiteSpace() const
{

        MyString strTemp = stripWhiteSpace();
        string::size_type len = strTemp.length();
        char *s = new char[len];
        strcpy(s,strTemp.c_str());
        char *p;
        char *token=" \t\n\v\f";
        string strret = strtok(s,token);
        while ( p=strtok(NULL,token) ) strret +=p;
        delete [] s;
        return strret;

}

/////////////file main.cpp
#include <iostream>
using namespace std;
#include "mystring.h"
int main(void)
{       
                MyString ilbc = "   asdfl   \n      lkeop;      llel'        ";
                ilbc = ilbc.simplefyWhiteSpace();
        cout << ilbc << endl;
        return 0;
}

在linux下面,我用g++编译后运行能得到正确的结果..
但是在Win下面我用Vc编译能通过.但是运行时提示Debug Error.如果我把 delete [] s 这条语句注释掉,在Vc下面就能运行得到正确的结果...
why?
发表于 2005-8-29 22:08:45 | 显示全部楼层
是你的程序的问题,注意下面这两句:

  1. string::size_type len = strTemp.length();
  2. char *s = new char[len];
复制代码

s只有len长度是肯定不够的,应该是len+1,原因你应该知道了.

ps:如果你使用2.3.5的glibc,运行时可能也会出问题的.
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-8-31 09:34:35 | 显示全部楼层

多谢啦................

多谢啦................
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表