C++ 按引用调用和ostream与字符串操作递归

C++ 按引用调用和ostream与字符串操作递归,c++,recursion,reference,overflow,call,C++,Recursion,Reference,Overflow,Call,全部! 我试图让我的程序正常工作,我不认为它应该是递归的。程序应该在文本文件中打印某些字符串,并将它们放在一个文本框中。 然而,我错误地修改了它,并做了一个无限循环(实际上是堆栈溢出,哈哈,多么有趣…)。任何帮助都将不胜感激。 以下是原型的代码(是的,使用了include): 以及主功能和子程序中的部分: cout << "Part c: textBox(text)" << endl ; cout << "---------------------"

全部! 我试图让我的程序正常工作,我不认为它应该是递归的。程序应该在文本文件中打印某些字符串,并将它们放在一个文本框中。 然而,我错误地修改了它,并做了一个无限循环(实际上是堆栈溢出,哈哈,多么有趣…)。任何帮助都将不胜感激。 以下是原型的代码(是的,使用了include):

以及主功能和子程序中的部分:

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(' ') ;       
}

cout它是递归的,因为
textBox
调用自身。如果您:

A) 在
textBox

或者B)将
文本框制作成如下:

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(' ') ;
}

并在
main

格式中调用上述函数有助于使代码可读。每次调用函数
textBox
,都会一次又一次地调用它……它是递归的,因为
textBox
会调用自身。myFile.txt的预期输出是什么?您的意思是在
文本框中调用不同的函数吗?也许你根本不应该在那里调用函数。字符串“框中的字符串”等应该通过文本框输出到文本文件。太基本了:“为什么我的递归调用会导致递归调用?”这不是答案。@TriHard8我已经修改了它。希望OP接受你的答案。我甚至不认为他们知道自己在做什么。@TriHard8是的,似乎很明显,函数不能在每个返回路径上调用自己。
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);
}