Re: stream input

Discussion in 'C++' started by Dietmar Kuehl, Aug 24, 2004.

  1. Aleks Dubinskiy wrote:
    > It seems to be very difficult to replace this with a convenient input

    stream
    > version, such as:
    > input>>"prfl num: ">>nPrflNum;


    The easiest "solution" is unfortunately not really portable as it
    assumes that you can overload a function in namespace 'std':

    namespace std {
    std::istream& operator>> (std::istream& in, char const* str) {
    int i = 0;
    for (char c; str && in.get(c) && c == str; ++i)
    ;
    if (str)
    in.setstate(std::ios_base::failbit);
    return in;
    }
    }

    A portable solution involves writing some word for each use, i.e.
    you would write a manipulator:

    struct expect {
    expect(char const* s): m_str(s) {}
    char const* m_str;
    };
    std::istream& operator>> (std::istream& in, expect const& e) {
    int i = 0;
    for (char c; e.m_str && in.get(c) && c == e.m_str; ++i)
    ;
    if (e.m_str)
    in.setstate(std::ios_base::failbit);
    return in;
    }

    This is used like this:

    std::cin >> expect("expect: ") >> whatever;
    --
    <mailto:> <http://www.dietmar-kuehl.de/>
    <http://www.contendix.com> - Software Development & Consulting
     
    Dietmar Kuehl, Aug 24, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Rasmusson, Lars
    Replies:
    1
    Views:
    783
    popov
    Apr 30, 2004
  2. Replies:
    9
    Views:
    676
    Alex Buell
    Apr 27, 2006
  3. Alexander Korsunsky

    get stream mode flags from an opened stream

    Alexander Korsunsky, Feb 17, 2007, in forum: C++
    Replies:
    1
    Views:
    478
    John Harrison
    Feb 17, 2007
  4. dolphin
    Replies:
    6
    Views:
    596
    Thomas Fritsch
    Mar 18, 2007
  5. Kashif Ur Rehman
    Replies:
    2
    Views:
    899
    Tom Hawtin
    May 17, 2007
Loading...

Share This Page