【问题标题】:Error: a function-definition is not allowed here before '{' token at line 6错误:在第 6 行的 '{' 标记之前不允许函数定义
【发布时间】:2020-01-25 14:53:37
【问题描述】:

我试图在一个名为 Password.txt 的 .txt 文件中获取此函数的输出。打印功能单独运行很容易,但是当我将它放在这个程序中以获取输出时,显示此错误:

错误:在第 6 行的 '{' 标记之前不允许函数定义

我尝试移除 void 但不起作用。

#include<iostream>
#include <fstream>

using namespace std;
void passn1()
{
   void print(char set[],string pre,int n,int k)
   {
       if(k==0)
       {
            cout<<pre<<endl;
            return;
       }
       for(int i=0;i<n;i++)
       {
            string newp;
            newp=pre+set[i];
            print(set,newp,n,k-1);
       }
   }
   void printk(char set[],int k,int n)
   {
       print(set,"",n,k);
   }
   ptk()
   {
        char set1[]={'0','1','2','3','4','5','6','7','8','9'};
        int k=6;
        printk(set1,k,10);
   }
}
int main()
{
    ofstream fo;
    fo.open("Password.txt",ios::out);
    fo<<passn1();
    fo<<endl;
    fo.close();
    return 0;
}

请告诉我哪里出错了。

【问题讨论】:

  • “告诉我我哪里出错了” - 你在这里出错了:void passn1() { void print(... - 你不能嵌套函数声明。

标签: c++ function file-handling


【解决方案1】:

您正试图在另一个函数的主体内定义一个函数,这是不允许的,正如编译器错误所暗示的那样。

此外,您不能向 std::ofstream 发送函数调用 (fo&lt;&lt;passn1();),这没有任何意义,因为函数的返回类型是 void(它什么也不返回)。

由于您有一个递归函数 (print()),最简单的方法是将输出流作为函数中的参数写入文件 (std::ofstream),然后将 pre 直接写入其中。当然,你需要在函数链中携带这个 ofstream 参数。

把所有东西放在一起,你会是这样的:

#include <iostream>
#include <fstream>

using namespace std;

void print(char set[], string pre, int n, int k, ofstream& fo)
{
    if(k==0)
    {
        fo << pre << endl;
        return;
    }
    for(int i=0;i<n;i++)
    {
        string newp;
        newp=pre+set[i];
        print(set, newp, n, k-1, fo);
    }
}

void printk(char set[],int k,int n, ofstream& fo)
{
    print(set, "", n, k, fo);
}

void ptk(ofstream& fo)
{
    char set1[]={'0','1','2','3','4','5','6','7','8','9'};
    int k=6;
    printk(set1, k, 10, fo);
}

int main()
{
    ofstream fo;
    fo.open("Password.txt",ios::out);
    ptk(fo);
    fo<<endl; // this will append an empty line at the end of the file
    fo.close();
    return 0;
}

输出(Password.txt 的内容):

000000
000001
// rest of the data here...
999998
999999

【讨论】:

  • “您不能向 std::ofstream 发送函数调用 (fostd::string 则有意义或定义了合适的operator&lt;&lt; 的其他类型。但是我当然同意当有问题的函数返回void时没有意义。
  • @JesperJuhl 对不起,我澄清了,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 2023-02-13
  • 1970-01-01
  • 2010-12-25
  • 1970-01-01
相关资源
最近更新 更多