【问题标题】:Call by reference and ostream and string manipulation recursive通过引用调用以及 ostream 和字符串操作递归
【发布时间】:2015-11-05 04:34:22
【问题描述】:

全部! 我试图让我的程序正常工作,但我认为它不应该是递归的 该程序应该在文本文件中打印某些字符串并将它们放在一个文本框中。 但是,我修改错了,做了一个无限循环(其实是堆栈溢出,哈哈,好笑……)。任何帮助将非常感激。 这是原型的代码(是的,使用了#include):

void textBox(ostream & out, string text);

以及主函数和子程序中的部分:

cout << "Part c: textBox(text)" << endl ;
    cout << "---------------------" << endl ;
    ofstream fout("myFile.txt");
    string box = "Text in a Box!";
    textBox(fout, box);

    fout << endl;
string size = "You can put any text in any size box you want!!";
textBox(fout,size);

fout << endl;
string courage = "What makes the muskrat guard his musk? Courage!";
textBox(fout,courage);

void textBox(ostream & out, string text)
{
    // ---------------------------------------------------------------------
    //  This routine outputs text surrounded by a box.
    // ---------------------------------------------------------------------

    ofstream myFile("myFile.txt");
    textBox(cout, "Message to screen");
    textBox(myFile, "Message to file");
    int textSize = text.size();

    out << '+' << setfill('-') << setw(textSize+1) << right << '+' << endl;
    out << '|' << text << '|' << endl;
    out << '+' << setfill('-') << setw(textSize+1) << right << '+' << endl;

    out << setfill(' ') ;       
}

【问题讨论】:

  • 格式化有助于使您的代码具有可读性。
  • 每次你调用函数textBox,你都会一遍又一遍地调用它……
  • 它是递归的,因为textBox 调用自己。 myFile.txt 的预期输出到底是什么?您的意思是在textBox 中调用不同的函数吗?也许你根本不应该在那里调用函数。
  • 字符串“String in a Box”等应该由textBox输出到文本文件中。
  • 太基础了:“为什么我的递归调用会导致递归调用?”

标签: c++ recursion reference overflow call


【解决方案1】:

它是递归的,因为textBox 调用自己。如果您满足以下条件,您的程序将运行:

A) 在textBox 中删除对textBox 的两个调用

或 B) 像这样制作textBox

void textBox(ostream & out, string text)
{
    int const textSize = text.size() + 1;

    out << '+' << setfill('-') << setw(textSize) << right << '+' << endl;
    out << '|' << text << '|' << endl;
    out << '+' << setfill('-') << setw(textSize) << right << '+' << endl;

    out << setfill(' ') ;
}

并创建另一个函数:

void textBoxWithInfo(ostream & out, string text)
{
    textBox(cout, "Message to screen");

    { // Braces to deallocate + close myFile faster
        ofstream myFile("myFile.txt");
        textBox(myFile, "Message to file");
    }

    textBox(out, text);
}

并在main中调用上述函数。

【讨论】:

  • 这不是答案。
  • @TriHard8 我已经修改过了。
  • 希望 OP 接受您的回答。我什至认为他们不知道自己在做什么。
  • @TriHard8 是的,看起来应该很明显一个函数不能在每个返回路径上调用自己。
猜你喜欢
  • 1970-01-01
  • 2016-04-09
  • 2020-10-04
  • 2019-05-11
  • 2012-10-10
  • 2013-03-15
  • 2018-08-13
  • 2014-08-11
  • 2017-07-25
相关资源
最近更新 更多