Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我可以在main之前创建fstream吗? #包括 #包括 使用名称空间std; 流fout(argv[1]);_C++_Fstream - Fatal编程技术网

C++ 我可以在main之前创建fstream吗? #包括 #包括 使用名称空间std; 流fout(argv[1]);

C++ 我可以在main之前创建fstream吗? #包括 #包括 使用名称空间std; 流fout(argv[1]);,c++,fstream,C++,Fstream,主要功能 #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; } #inclu

主要功能

#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;
}
#include <string.h>
#include <fstream>

using namespace std;

string argument;
ofstream fout(argument]);
int main(int argc,const char*argv[]{
//我尝试添加“新单词”fstream文件

fout在你知道什么是
argv
之前,你不能初始化你的
fout
。因此,从某种意义上说,这是不可能的。但是,你可以不用任何东西初始化它,然后在你得到
argv
后打开它:

int main(int argc, const char * argv[]) {
argument=argv[1]
fout<<"new words"<<endl;
}
流源的
;
int main(int argc,const char*argv[]
{
fout.open(argv[1]);

foutIs这是的副本?您将在这里得到相同的建议。为什么它必须“在主函数之前”?这似乎是一个无法满足的任意要求。您不能基于尚未调用的函数的参数打开文件“我可以在主函数之前创建流吗?”是的。“我可以在main之前使用
argv
?"不。不,这不是同一个问题,但当我看到这个问题时,我想知道它。它可能与操作系统API(如
GetCommandLine
)有关。可能-文档中没有说明它在
main
之前是否有效。即使有效,我也无法想象需要它的有用需求。@b219请注意,您现在已经知道了有一个全局变量,必须密切关注它。它完全暴露在外,任何人都可以搞乱它。甚至是其他翻译单元中的代码。这使得调试和审核代码的正确性变得比必要的更困难,因此它需要有一个大的回报,使它可能造成的痛苦是值得的。我知道这是我刚开始学习c++的时候,我有一个任务需要尽快完成。我知道这是不对的,但我必须这样做,我的任务才能正常工作。
ofstream fout;

int main(int argc, const char * argv[])
{
    fout.open(argv[1]);
    fout<<"new words"<<endl;
}