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

时间:2013-11-30 20:50:58

标签: c++ file-io iostream

我试过四处寻找并搜索答案。它不会在我的文档文件夹中创建.txt文件。无论我尝试什么,我都没有得到任何错误,代码运行直到主要结束。 1.我的意见是正确的。我和cout一起检查过。 我正在把我的目录作为我的目录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;

   }

2 个答案:

答案 0 :(得分:0)

看来,你忘了在最后关闭文件。尝试添加ost.close()以指示您的流刷新到文件。

答案 1 :(得分:-1)

尝试将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;
//...
}