c++ - 创建输入流操纵器

标签 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(&stuff,'/') 会吸收 iss 中的字符,直到它遇到/。我可以使用调试器观看它,因为它通过“/”获取字符“n”“o”“w” 并终止循环。在我看到 Stuff 之前,一切似乎都在顺利进行。 Stuff 现在有字符等但是每个字符之间还有 6 个额外的字符。这是一个示例:

  • &quitt 0x0012fba4 {0x008c1861“nì确实

这是怎么回事?

最佳答案

这一行:

SIU.S->append(&N);

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

您可以组成一个小的以 null 结尾的 char 数组并将其传入,或者您可以使用另一个附加函数来附加一个计数和一个字符:

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

关于c++ - 创建输入流操纵器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3580621/

相关文章:

c++ - 为什么 iostream 对象不重载 operator bool?

c++ - clang 拒绝模板 `/` 运算符但 gnu c++ 接受它

c++ - 在 OpenCL 中为嵌入式配置文件创 build 备上下文

c++ - MFC IMPLEMENT_DYNCREATE 模板

c++ - 使用 automake 安装 header

c++ - 升级到CUDA 11时cudaError/CUresult不兼容

c++ - 好友ostream无法访问私有(private)成员(member)

(s)printf 的 C++ 标准替代品

c++ - 为什么我不能使用 std :cin as an argument

c++ - istream_iterator,黑魔法?