如何让我的c++程序创建一个新文件
How do I get my c++ program to create a new file?
我试过四处打听并在谷歌上搜索答案。它不会在我的文档文件夹中创建.txt文件。无论我尝试了什么,我都没有得到任何错误,代码一直运行到main的末尾。1.我的输入是正确的。我向海关核实了一下。2.我将C:\users\Bryan \Documents\Points.txt 作为目录
int main()
{
//...
std::string filename;
cout << "Enter output filename: ";
std::getline(cin, filename);
ofstream ost(filename.c_str());
if (!ost) cerr << "can't open output file: " << filename << endl;
for(int i=0; i<points.size(); ++i)
ost<<'('<<points[i].x<<','<<points[i].y<<')'<<endl;
cout <<"got here 6"<<endl;
//...
}
我添加了close(),但忘记了返回0,它只起了一次作用。然后我添加了返回0,无论我尝试多少次,它都不会创建新文件,但不会引发错误。我看不出我做错了什么。任何人
int main()
{
cout <<"got here 1"<<endl;
cout << "Please enter the file name: ";
char name[90];
cin.getline(name, 90);
cout <<"got here 2"<<endl;
ifstream ifs(name);
if(!ifs) error("can't open input file ",name);
vector<Point> points;
Point p;
while(ifs>>p)points.push_back(p);
cout <<"got here 3"<<endl;
for(int i=0; i<points.size(); ++i)
cout<<'('<<points[i].x<<','<<points[i].y<<')'<<endl;
std::string filename;
cout << "Enter output filename: ";
std::getline(cin, filename);
ofstream ost(filename.c_str());
if (!ost) cerr << "can't open output file: " << filename << endl;
for(int i=0; i<points.size(); ++i)
ost<<'('<<points[i].x<<','<<points[i].y<<')'<<endl;
cout <<"got here 6"<<endl;
ost.close();
keep_window_open();
return 0;
}
您似乎忘记了在最后关闭文件。尝试添加ost.close()来指示流刷新到文件中。
尝试将std::ofstream::out添加到ofstream构造函数中,并使用isOpen检查文件是否真的打开。
int main()
{
//...
std::string filename;
cout << "Enter output filename: ";
std::getline(cin, filename);
ofstream ost(filename.c_str(), std::ofstream::out);
if (!ost.isOpen()) cerr << "can't open output file: " << filename << endl;
for(int i=0; i<points.size(); ++i)
ost<<'('<<points[i].x<<','<<points[i].y<<')'<<endl;
cout <<"got here 6"<<endl;
//...
}
相关文章:
- 如何使用CLion在Mac上创建一个新的.txt文件
- 如何创建一个新的二进制文件并用常量值填充它?
- 如何限制文件大小,以便我的程序在变大之后创建一个新文件?并编辑新创建的文件的名称
- boost::log关闭日志文件并打开一个新文件
- 在 Eclipse ADT 中,我创建了一个新的 cpp 文件并收到"undefined reference"错误
- 使用std :: ifstream打开一个新文件
- Pantheios:当太大时创建一个新的日志文件
- 从一个字符串复制到另一个字符串并粘贴到新文件中
- 如何将XML文件拆分为多个XML,以便每个新文件只包含原始文件中的一个文本节点
- 如何让我的c++程序创建一个新文件
- 需要使用 QFileDialog 保存一个新文件
- 找到文本文件中的最后一行,选择前10个字符并打印到一个新文件中
- 在Qml中创建一个新文件夹
- 在SDL中创建一个新文件夹或目录
- 如何使用c++在%APPDATA%中创建一个新文件夹
- Ofstream,什么时候它会失败而不是创建一个新文件
- 使用eclipse cdt在c++中包含一个新文件
- 是否有可能使用log4cXX为每一天创建一个新文件
- 使用 /Command 选项从命令行为 Visual Studio C++ 项目创建一个新文件
- 创建一个新文件(如果不存在)