gpt4 book ai didi

c++ - 错误:第6行 '{' token 之前不允许在此处进行功能定义

转载 作者:行者123 更新时间:2023-12-01 15:13:32 24 4
gpt4 key购买 nike

我正在尝试在名为Password.txt的.txt文件中获取此函数的输出。要打印的函数可以轻松单独运行,但是当我将其放入该程序以获取输出时,此错误显示:

Error: a function-definition is not allowed here before '{' token at line 6



我试图删除无效但无法正常工作。
#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;
}

请告诉我哪里出问题了,以帮助我。

最佳答案

您试图在另一个函数体内定义一个函数,这是不允许的,因为编译器错误提示。

而且,您不能向std::ofstream发送函数调用(fo<<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

关于c++ - 错误:第6行 '{' token 之前不允许在此处进行功能定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59910361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com