You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ PPP第8章练习1:修改计算器Token_stream支持istream参数问题求助

实现步骤

你只需要做3处核心改动即可完成需求:

1. 修改Token_stream类定义,添加输入流成员和对应构造函数

因为istream不可复制,所以用引用类型存储输入流,完全符合题目提示的要求。

#include <istream>
using std::istream;

class Token_stream {
public:
    // 新增构造函数,接收istream引用初始化输入流成员
    explicit Token_stream(istream& is) : input(is) {}
    Token get();                // get a Token
    void putback(Token t);      // put a token back
    void ignore(char c);        // discard characters up to and including a c
private:
    bool full{ false };        // is there a Token in the buffer?
    Token buffer{ '0' };  
    istream& input; // 新增成员:存储输入流引用,不复制流本身
};

2. 替换Token_stream::get方法中所有硬编码的cin

把所有调用cin的地方全部替换为你新增的istream引用成员即可:

Token Token_stream::get()
{
    if (full) {             // do we already have a Token?
        full = false;       // remove Token from buffer
        return buffer;
    }

    char ch;
    input.get(ch);            // 替换原cin为input

    while (isspace(ch) && ch != '\n') input.get(ch);

    switch (ch) {
    case '\n':
        return Token{ print };
    case print:
    case quit:
    case help:
    case '(':
    case ')':
    case '{':
    case '}':
    case '!':
    case '+':
    case '-':
    case '*':
    case '/':
    case '%':
    case '=':
    case ',':
        return Token{ ch };    // let each character represent itself
    case '.':
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
    {
        input.putback(ch);    // 替换原cin为input
        double val;
        input >> val;         // 替换原cin为input
        return Token{ number, val };
    }
    default:
        if (isalpha(ch)) {
            string s;
            s += ch;
            while (input.get(ch) &&
                ((isalpha(ch) || isdigit(ch) || ch == '_')))
                s += ch;
            input.putback(ch); // 替换原cin为input
            if (s == declkey) return Token{ let };    // declaration keyword
            else if (s == sqrtkey) return Token{ square_root };
            else if (s == expkey) return Token{ exponent };
            else if (s == sinkey) return Token{ c_sin };
            else if (s == coskey) return Token{ c_cos };
            else if (s == quitkey) return Token{ quit };
            else if (s == helpkey) return Token{ help };
            else return Token{ name, s };
        }
        error("Bad token");
    }
}

3. 其他配套修改

  • 如果Token_stream::ignore方法中也用到了cin,同样替换为该istream引用成员
  • 原代码中创建Token_stream实例的地方,改为传入对应的输入流:
    • 仍使用标准输入的写法:Token_stream ts(std::cin);
    • 使用文件输入的写法:std::ifstream ifs("input.txt"); Token_stream ts(ifs);
    • 使用字符串流的写法:std::istringstream iss("1+2*3\n"); Token_stream ts(iss);

修改后所有计算逻辑不需要调整,只需要传入不同的输入流就能适配不同输入源,完全符合题目要求。

内容的提问来源于stack exchange,提问作者jaylse2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:24:03