Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.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++; 我似乎有一些问题想完成我的C++程序,并会得到一些帮助。_C++_File_Text Files_Output_Fstream - Fatal编程技术网

创建新文本文件C++; 我似乎有一些问题想完成我的C++程序,并会得到一些帮助。

创建新文本文件C++; 我似乎有一些问题想完成我的C++程序,并会得到一些帮助。,c++,file,text-files,output,fstream,C++,File,Text Files,Output,Fstream,在我的程序结束时,我需要它也输出到一个文本文件。我尝试过使用fstream和ofstream的各种方法来检查文件是否存在,如果存在,则创建一个新文件,尽管我运气不好 这就是我目前的位置,但如果“output.txt”存在,那么它只会删除其中的内容,不创建任何内容,但不会崩溃 ... ofstream output; int fileIncrement = 0; bool validFile = false; cout << "Saving File.." << endl

在我的程序结束时,我需要它也输出到一个文本文件。我尝试过使用fstream和ofstream的各种方法来检查文件是否存在,如果存在,则创建一个新文件,尽管我运气不好

这就是我目前的位置,但如果“output.txt”存在,那么它只会删除其中的内容,不创建任何内容,但不会崩溃

...
ofstream output;
int fileIncrement = 0;
bool validFile = false;

cout << "Saving File.." << endl;
output.open("output.txt");

while (!validFile)
{
    if (output.good()) //  does exist
    {
        fileIncrement++;
        output.open(to_string(fileIncrement) + "output.txt");
    }
    else
    {
        myVectors.outputVectors(output);
        validFile = true;
    }
}
。。。
流量输出;
int fileIncrement=0;
bool-validFile=false;
coutoutput.good()只检查文件的可访问性。如果它还不存在,它将被创建。因此,船长不经意地评论说validFile永远不会被设置为true。函数结束的原因实际上是因为在打开第二个文件()之前忘记关闭第一个文件。该操作失败,设置失败位。这就是为什么你的新文件永远不会被创建,而你以前的文件会被覆盖


我不确定有一个伟大的标准的方法来检查C++中的文件的预先存在,但听起来像是你想要的。< /P>因为如果输出文件被打开(<代码>好< /COD>返回true),第一个条件-<代码> IF(输出。

-始终为true,并且
validFile
从未设置为
true
。不过它确实完成了。我认为output.open(to_string(fileIncrement+“output.txt”);会更改打开的文件,从而生成一个新的文件?…它是正确的,并且完成了,所以它不会在启动调试程序并逐步完成代码时陷入循环。我已经完成了。它很好,这就是为什么我如此困惑的原因。如果需要,我会检查文件“output.txt”已经存在,然后它只是删除其内容,但从未创建“1output.txt”,就像它应该创建的logicI添加的output.close();Underneeth validFile=true;仍然没有运气