0

Bruce Eckel の「Thinking in C++」の助けを借りて C++ を学習します。「Iostreams」の章の演習 05 で行き詰まりました:

演習テキスト

setw( ) で最小限の文字数しか読み取れないことはわかっていますが、最大数の文字数を読み取りたい場合はどうすればよいでしょうか? ユーザーが抽出する文字の最大数を指定できるようにするエフェクターを作成します。幅の制限内に収まるように、必要に応じて出力フィールドが切り捨てられるように、エフェクターを出力用にも機能させます。

パラメータを使用しない場合と使用する場合の両方でマニピュレータを作成する方法を理解しています (本の用語ではエフェクタと呼ばれます)。ただし、抽出する最大文字数を制限する方法がわかりません。std::ios_base::width最小文字数を指定します。

streambuf基になるオブジェクトでいくつかのトリックを行う必要がありますか?

4

2 に答える 2

2
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
using namespace std;    
class fixW{
    char* chrP;
    char str[1024];
    size_t Max;
    public:
    fixW(char* p,size_t m=25):chrP(p),Max(m){}

    friend istream& operator >>(istream& is,fixW fw){
        is >>fw.str;
        size_t n=strlen(fw.str);
        cout <<" n= "<<n << endl;
        if(n>=25){
            fw.str[fw.Max]='\0';
        }

        strcpy(fw.chrP,fw.str);
        return is;
    }

    friend ostream& operator<<(ostream& os, fixW fw){
        for(size_t i= 0; i<fw.Max; ++i){
            fw.str[i] = fw.chrP[i];
        }

        fw.str[fw.Max]='\0';
        return os <<fw.str;
    }
};
int main(){
    char s[80];
    cin >> fixW(s,25);
    cout << s << endl;
    cout << fixW(s,10)<<endl;
    cout << s <<endl;
    return 0;
}
于 2012-12-17T08:13:21.980 に答える
1

これは完璧な解決策ではありません(ただし、現時点では、iostreamライブラリを読まないと別の方法を考えることはできません)。

マニピュレータは次のとおりです。

class MaxFieldSize {/*STUFF*/};

ストリーム演算子を作成するときは、実際のストリームを返さない(むしろ、ラッパーを含むストリームを返す)少しファンキーな演算子を作成します。

MaxFieldWdithStream operator<<(std::ostream&, MaxFieldSize const& manip);

ここで、このクラスのすべてのストリーム演算子をオーバーロードして、通常のストリームオブジェクトを返す前に入力を切り捨てます。

class MaxFieldWithStream { std::ostream& printTruncatedData(std::string& value);};

次に、必要なのは一般的なオーバーロードだけです。

template<typename T>
std::ostream& operator<<(MaxFieldWithStream& mfwstream, T const& value)
{
    std::stringstream  trunStream;
    trunStream << value;

    return mfwstream.printTruncatedData(trunStream.substr(0, mfwstream.widthNeeded));
}
// You will probably need another overload for io-manipulators.

また、MaxFieldWithStreamをstd :: iostreamに自動的に変換する変換演算子を追加して、関数に渡された場合でもストリームのように動作するようにします(ただし、max widthプロパティは失われます)。

class MaxFieldWithStream
{
    std::ostream& printTruncatedData(std::string& value);};
    operator st::ostream&() const { return BLABLAVLA;}
};
于 2012-11-30T14:58:50.003 に答える