1

问题

问题是我正在尝试使用插入运算符获取用户输入并初始化值thechars,以将大小分配给我需要输入长度的字符,我如何获得它?并在插入运算符中初始化。

主要问题是插入运算符。

当我运行程序时,它显示分段错误,

请帮助

class string1
{    
  private:
    int len;
    char *thechars;

    //friend ostream& operator<<(ostream&,string1&);##
    //friend istream& operator>>(istream&,string1&);##

  public:
    //string1() :len(0),thechars(NULL){}
    string1()
    {
      thechars = new char[1];
      thechars[0] = '\0';
      len=0;
      // cout << "\tDefault string constructor\n";
      // ConstructorCount++;
    }
};

// this is the insertion operator i use
istream& operator>>(istream& in, string1& tpr)
{
  in >> tpr.thechars;
  //tpr.thechars[i+1]='\0';
  return in;
}

//this one is the extraction operator
ostream& operator<<(ostream& out,string1& prt)
{
  for(int i=0;i<prt.len;i++)
    out<<prt.thechars[i];

  return out;
}

// main function##
string1 str;
cout << "enter first string" << endl;
cin >> str;
cout << str << endl;
4

3 回答 3

2

如果in是文件输入流,可以执行以下操作:

in.seekg(0, ios::end);
length = in.tellg();
in.seekg(0, ios::beg);

另一种选择是逐个字符地读取输入流,并在thechars每次用完时将其大小加倍。首先,再引入一个变量来存储当前分配的缓冲区大小 --- allocSize。之后更新构造函数,operator<<如下所示。

构造函数:

string1()
{
    allocSize = 1; // initially allocated size
    thechars = new char[allocSize];
    thechars[0] = '\0';
    len=0;
}

输入运算符:

istream& operator>>(istream& in, string1& tpr)
{
    char inp;
    while (in.get(inp)) {
        // end-of-input delimiter (change according to your needs)
        if (inp == ' ')
            break;
        // if buffer is exhausted, reallocate it twice as large
        if (tpr.len == tpr.allocSize - 1) {
            tpr.allocSize *= 2;
            char *newchars = new char[tpr.allocSize];
            strcpy(newchars, tpr.thechars);
            delete[] tpr.thechars;
            tpr.thechars = newchars;
        }
        // store input char
        tpr.thechars[tpr.len++] = inp;
        tpr.thechars[tpr.len] = '\0';
    }
}

但最好的选择是std::string用作thechars. 你真的需要所有这些手动内存处理吗?

于 2012-05-25T07:39:55.410 回答
1

而不是给inachar*给它一个常规字符串。然后你可以自己提取数据。

istream& operator>>(istream& in, string1& tpr)
{
  string temp;
  in >> temp;
  tpr.len = temp.length + 1;
  tpr.thechars = new char[tpr.len];
  tpr.thechars[temp.length] = '\0';
  strcpy(tpr.thechars, &temp[0], tpr.len);
  return in;
}
于 2012-05-25T07:58:37.293 回答
0

你写了

 in>> tpr.thechars; // where thechars="\0"; 

你只分配了一个字节,但我猜你输入的字符串有更多字节。我认为这里有错误。

于 2012-05-25T07:43:13.043 回答