创建输入流操纵器

时间:2010-08-27 00:56:49

标签: c++ iostream

作为一个练习,我正在尝试创建一个输入流操纵器,它将吸收字符并将它们放在一个字符串中,直到它遇到一个特定字符或直到它到达eof。这个想法来自Bruce Eckel的“Thinking in c ++”第249页。

这是我到目前为止的代码:

#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;
    }
};

并测试它....

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

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

想法是siu(&amp; stuff,'/')会从iss中吸收字符,直到遇到/。我可以通过调试器观察它,因为它通过'/'获得字符'n''''w' 并终止循环。在看到Stuff之前,这一切似乎都在游荡。东西现在有角色等但每个角色之间有6个额外的角色。这是一个样本:

  • &amp; stuff 0x0012fba4 {0x008c1861“nÌÌÌÌÌÌÌÌÌ”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”

发生了什么事?

1 个答案:

答案 0 :(得分:3)

这一行:

SIU.S->append(&N);

将角色附加为char *。 append函数期望一个以空字符结尾的字符串,因此它不断读取&amp; N,(&amp; N)+1 ......直到它看到一个零字节。

你可以组成一个小的null终止的char数组并传入它,或者你可以使用一个带有count和一个字符的替代append函数来追加:

SIU.S->append(1, N);
相关问题