【问题标题】:Why is the stringstream variable not taking my second input?为什么 stringstream 变量不接受我的第二个输入?
【发布时间】:2021-09-18 10:13:18
【问题描述】:

Node 具有 1 个默认构造函数的类:-

class Node
{
public:
    int data;
    Node* left, * right;

    Node(const int data = 0)
    {
        left = right = nullptr;
        this->data = data;
    }
};

main 函数来测试create_tree 是否工作:-

int main()
{
    std::cout << "enter the elements of the tree.\n";
    std::string s{};
    getline(std::cin, s);
    std::stringstream ss{};
    ss << s;
    std::queue<std::string> q;
    Node* root{ new Node() };

    while (ss.good())
    {
        ss >> s;
        q.push(s);
    }

    create_tree(root, q);

    std::cout << "root = " << root->data << "\n";
    std::cout << "root->right = " << root->right->data << "\n";

    return 0;
}

通过使用root 节点和字符串队列q 创建二叉树的函数:-

void create_tree(Node*& root, std::queue<std::string> q)
{
    std::queue<Node*> ptr;

    if (q.empty() || q.front() == "N")
    {
        root = nullptr;
        return;
    }

    std::stringstream ss{};
    ss << q.front() << " ";                             //ss << q.front();
    q.pop();
    ss >> root->data;
    ptr.push(root);

    while (!q.empty() && !ptr.empty())
    {
        if (q.front() != "N")
        {
            ptr.front()->left = new Node();
            ss << q.front() << " ";                     //ss << " " << q.front();
            ss >> ptr.front()->left->data;
            ptr.push(ptr.front()->left);
        }

        q.pop();

        if (!q.empty())
        {
            if (q.front() != "N")
            {
                ptr.front()->right = new Node();
                ss << q.front() << " ";                 //ss << " " << q.front();
                ss >> ptr.front()->right->data;
                ptr.push(ptr.front()->right);
            }
            
            q.pop();
        }

        ptr.pop();
    }
}

INPUT 以整数和“N”的级别顺序给出。 'N' 用于表示在该Node 中不会发生进一步的分支。

输入:-

1 2 3

期望的输出:-

root = 1
root->right = 3

create_tree 中,如果我用注释语句替换语句(其右侧有 cmets),则程序无法运行。当程序在create_tree 内时; ss 没有在 while 循环中获取任何值。我想知道为什么?

【问题讨论】:

    标签: c++ queue binary-tree stringstream


    【解决方案1】:

    因为 std::stringstream 正在寻找第一个分隔符(默认为空格)并据此进行标记,所以它也保持它停止的状态。

    第一次,没有分隔符,所以它在最后完成并且可以工作 第二次它在开始时找到空间,所以它标记了空间。

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 2021-08-17
      相关资源
      最近更新 更多