C++ 在文件上写入时没有输出
文件输出为空,任何代码都会出现此问题 注意:方向文件为trueC++ 在文件上写入时没有输出,c++,C++,文件输出为空,任何代码都会出现此问题 注意:方向文件为true #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile ("example.txt"); while (myfile.is_open()) { myfile << "This is a line.\n"; myfile <
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
while (myfile.is_open()) {
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
return 0;
}
首先确保文件已打开 那你可以试试这个
ofstream myfile ("example.txt" , ios::out);
尝试执行std::fstream myfile example.txt、std::ios\u base::out;如果文件无法打开怎么办?在这种情况下,您的代码没有任何作用……我看不出任何明显的错误。除非while应该是if。如果文件无法打开,则可以添加else并打印消息。或者,可能您正在查看错误的文件夹。删除example.txt,然后再次运行该程序。请尝试文件名的绝对路径,如/tmp/example.txt或c:\\example.txt。如果您在IDE中运行,通常情况下,您运行的目录与您认为的不同。不确定这是否有任何好处?第二个参数的默认值已超出。