1

質問

問題は、挿入演算子を使用してユーザー入力を取得し、値を初期化しようとしていることですthechars。入力の長さが必要な文字にサイズを割り当てるには、どうすればよいですか?そして、挿入演算子で初期化します。

主な問題は挿入演算子にあります。

プログラムを実行すると、セグメンテーション違反が表示されます。

plzヘルプ

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);

もう1つのオプションは、入力ストリームの文字を文字ごとに読み取り、thechars使い果たされるたびにサイズを2倍にすることです。まず、現在割り当てられているバッファのサイズを格納するための変数をもう1つ導入します--- 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

inaを指定する代わりにchar*、通常の文字列を指定します。その後、データを自分で抽出できます。

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"; 

1バイトしか割り当てていませんが、より多くのバイトを含む入力文字列だと思います。ここでエラーだと思います。

于 2012-05-25T07:43:13.043 に答える