我可以在 main 之前创建 fstream 吗?
Can I create fstream before main?
#include <string.h>
#include <fstream>
using namespace std;
ofstream fout(argv[1]);
主要功能
int main(int argc, const char * argv[]) {
//I try to add "new word" fstream file
fout<<"new words"<<endl;
}
我该怎么做?最下面的也没有用。这是必要的。必须在main函数之前
#include <string.h>
#include <fstream>
using namespace std;
string argument;
ofstream fout(argument]);
主要功能
int main(int argc, const char * argv[]) {
argument=argv[1]
fout<<"new words"<<endl;
}
在知道 argv
是什么之前,您无法初始化 fout
。所以,从某种意义上说,不可能。但是,您可以什么都不初始化它,并且 open
稍后当您获得 argv
:
ofstream fout;
int main(int argc, const char * argv[])
{
fout.open(argv[1]);
fout<<"new words"<<endl;
}
这样,全局 fout
可以被定义在它之后的所有函数访问。不过有一小段时间,在main
开启之前,fout
无效。从逻辑的角度来看,这是你能做的最好的事情。
#include <string.h>
#include <fstream>
using namespace std;
ofstream fout(argv[1]);
主要功能
int main(int argc, const char * argv[]) {
//I try to add "new word" fstream file
fout<<"new words"<<endl;
}
我该怎么做?最下面的也没有用。这是必要的。必须在main函数之前
#include <string.h>
#include <fstream>
using namespace std;
string argument;
ofstream fout(argument]);
主要功能
int main(int argc, const char * argv[]) {
argument=argv[1]
fout<<"new words"<<endl;
}
在知道 argv
是什么之前,您无法初始化 fout
。所以,从某种意义上说,不可能。但是,您可以什么都不初始化它,并且 open
稍后当您获得 argv
:
ofstream fout;
int main(int argc, const char * argv[])
{
fout.open(argv[1]);
fout<<"new words"<<endl;
}
这样,全局 fout
可以被定义在它之后的所有函数访问。不过有一小段时间,在main
开启之前,fout
无效。从逻辑的角度来看,这是你能做的最好的事情。