使用流写入文件内部

时间:2017-10-09 23:21:48

标签: c++

我应该在名为“mydata.txt”的文件中打印(x,y)值。但由于某种原因,我收到以下错误消息:“错误:无法打开输出文件mydata.txt”我不确定该程序是否应该创建文本文件或我应该创建该文件。我尝试了后者,它仍然无法正常工作。这是我的代码:

#include "std_lib_facilities_5.h"

class Point{
    public:

    int x;
    int y;

    // Coordinate members x and y
    Point(int nn = 0 , int mm = 0): x(nn), y(mm){}
    friend ostream& operator<< (ostream &out, const Point &point);
};

ostream& operator<<(ostream& os, const Point& point){
    os << point.x << " " << point.y;
    return os;
}

int main()
try {
    int x1, x2;
    vector<Point> original_points;

    for(int i = 0; i < 7; ++i) {
        cout << "Please input coordinate points as (x,y): ";
        cin >> x1 >> x2;
        original_points.push_back(Point(x1,x2));
    }
    for(int i = 0; i < 7; ++i){
        cout << "Original points: " << original_points[i] << endl;
    }
    string outputFile = "mydata.txt";
    ofstream ost {"mydata.txt"};
    ost.open(outputFile,ofstream::out);
    if(!ost) error("can't open output file ", outputFile);

    for(int i = 0; i < original_points.size(); ++i){
        ost << original_points[i] << " " << original_points[i];
    }
    ost.close();
}
catch (exception& e) {
    cerr << "error: " <<e.what() << '\n';
    return 1;
    }
    catch (...) {
        cerr << "Oops: unknown exception!\n";
        return 2;
    }

这是运行时的输出:

Please input coordinate points as (x,y): 1 2
Please input coordinate points as (x,y): 1 1 
Please input coordinate points as (x,y): 2 2 
Please input coordinate points as (x,y): 3 3 
Please input coordinate points as (x,y): 4 4 
Please input coordinate points as (x,y): 5 5 
Please input coordinate points as (x,y): 6 6
Original points: 1 2
Original points: 1 1
Original points: 2 2
Original points: 3 3
Original points: 4 4
Original points: 5 5
Original points: 6 6
error: can't open output file mydata.txt
Program ended with exit code: 1

2 个答案:

答案 0 :(得分:1)

ofstream ost {"mydata.txt"};打开该文件。

然后你在下一行再次打开它的尝试失败了,因为它已经打开了 删除第二行。

删除行ost.close();时,析构函数会在适当的时候为您关闭。

答案 1 :(得分:0)

试试这个

// Skip smudge - We'll download binary files later in a faster batch
git lfs install --skip-smudge

// Do git clone here
git clone ...

// Fetch all the binary files in the new clone
git lfs pull

// Reinstate smudge
git lfs install --force