简体   繁体   English

如何在创建的文本文件中保存我的 C++ 编译器输出?

[英]how to save my c++ compiler output in created text file?

I am making a simple compiler using c++ but the output shows in my console window only!我正在使用 C++ 制作一个简单的编译器,但输出仅显示在我的控制台窗口中!

class Scanner{
private:
    ifstream f;
    Token check_reserved(string s){
        if (s == "program") return PROGRAM_SY;
        else if (s == "is")return IS_SY;
        else if (s == "begin")return BEGIN_SY;
        else if (s == "end")return END_SY;
        else if (s == "var")return VAR_SY;
}

void display_tokens(void){
        Token t;
        if (f.eof())cout << "end_of_file " << endl;
        while (!f.eof()){
            t = get_token();
            switch (t){
            case PROGRAM_SY: cout << "program token" << endl; break;
            case IS_SY: cout << "is token" << endl; break;
            case BEGIN_SY: cout << "begin token" << endl; break;
            case END_SY: cout << "end token" << endl; break;
            }
        }

    }
};

int main(){

    ofstream myfile;
    myfile.open("example.txt");
    myfile << SC.display_tokens();
    myfile.close();

    string Filename;
    cout << "Enter Name of input File : ";
    cin >> Filename;
    Scanner SC(Filename);
    SC.display_tokens();
    SC.~Scanner();
}

I expected that my code will print my output in my console window in save it inside the text file.我希望我的代码将在我的控制台窗口中打印我的输出,并将其保存在文本文件中。 what is the problem here, and what is the right code to get my output?这里有什么问题,获取输出的正确代码是什么?

One issue is that functions need to return values in order for you to output the value to a stream.一个问题是函数需要返回值才能将值输出到流。

Your function declaration says that the function does not return a value:您的函数声明表示该函数不返回值:

void display_tokens(void)

Yet, you use the function as if it returns a value:但是,您可以像使用该函数一样返回一个值:

myfile << SC.display_tokens();

I recommend you review the subject of "functions" in your Compiler Theory book.我建议您查看编译器理论书中的“函数”主题。 Also, review "functions" in your favorite C++ book.另外,请查看您最喜欢的 C++ 书中的“函数”。

You could change the function:您可以更改功能:

void display_tokens(std::ostream& my_file)
{
    //...
    my_file << "Here are the tokens:\n";
    //...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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