简体   繁体   中英

creating input stream manipulator

As an exercise, I'm trying to create a input stream manipulator that will suck up characters and put them in a string until it encounters a specific character or until it reaches eof. The idea came from Bruce Eckel's 'Thinking in c++' page 249.

Here's the code I have so far:

#include <string>
#include <iostream>
#include <istream>
#include <sstream>
#include <fstream>
#include <iomanip>
using namespace std;

class siu 
{
    char T;
    string *S;
public:

    siu (string *s, char t)
    {
        T = t;
        S = s;
        *S = "";
    }


    friend istream& operator>>(istream& is, siu& SIU)
    {
        char N;
        bool done=false;
        while (!done)
        {
            is >> N;
            if ((N == SIU.T) || is.eof())
                done = true;
            else
                SIU.S->append(&N);
        }
        return is;
    }
};

and to test it....

        {
            istringstream iss("1 2 now is the time for all/");
            int a,b;
            string stuff, zork;

            iss >> a >> b >> siu(&stuff,'/');
            zork = stuff;
        }

the idea being that siu(&stuff,'/') will suck up characters from iss until it encounters the /. I can watch it with the debugger as it gets the characters 'n' 'o' 'w' through '/' and terminates the loop. It all seems to be going swimingly until I look at Stuff. Stuff has the characters now etc BUT there are 6 extra characters between each of them. Here's a sample:

  • &stuff 0x0012fba4 {0x008c1861 "nÌÌÌýoÌÌÌýwÌÌÌýiÌÌÌýsÌÌÌýtÌÌÌýhÌÌÌýeÌÌÌýtÌÌÌýiÌÌÌýmÌÌÌýeÌÌÌýfÌÌÌýoÌÌÌýrÌÌÌýaÌÌÌýlÌÌÌýlÌÌÌý"}

What's going on?

This line:

SIU.S->append(&N);

appends the character as a char *. The append function is expecting a null terminated string, so it keeps reading from &N, (&N)+1... until it sees a zero byte.

You can either make up a small null terminated char array and pass that in, or you can use the an alternate append function that takes a count and a character to append:

SIU.S->append(1, N);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM