如何让我的c++程序创建一个新文件

How do I get my c++ program to create a new file?

本文关键字:一个 新文件 文件 c++ 我的 程序 创建      更新时间:2023-10-16

我试过四处打听并在谷歌上搜索答案。它不会在我的文档文件夹中创建.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;
//...
}