簡體   English   中英

ifstream 不從文件中讀取值

[英]ifstream doesn't read values from the file

我正在制作一個處理點和文件的程序。 我沒有警告或錯誤,但它仍然無法正常工作。 我認為問題出在 ifstream 上,導致 ofstream 運行良好並將輸入的值放入文件中。

我得到的輸出看起來像這樣

Please enter seven (x,y) pairs:
//here the seven pairs are entered

These are your points: 
//(...,...)x7 with the values

These are the points read from the file: 
//and the program ends and returns 0

我希望有一個人可以幫助我。 這是我的代碼。

#include <iostream>
#include "std_lib_facilities.h"

using namespace std;

struct Point{
    float x;
    float y;
};

istream& operator>>(istream& is, Point& p)
{
    return is >> p.x >> p.y;
}

ostream& operator<<(ostream& os, Point& p)
{
    return os << '(' << p.x << ',' << p.y << ')';
}

void f() {
    vector<Point> original_points;
    cout << "Please enter seven (x,y) pairs: " << endl;
    for (Point p; original_points.size() < 7;) {
        cin >> p;
        original_points.push_back(p);
    }
    cout << endl;
    cout << "These are your points: " << endl;
    for (int i=0; i < 7; i++) {
        cout << original_points[i] << endl;
    }
    string name = "mydata.txt";
    ofstream ost {name};
    if (!ost) error("can't open output file", name);
    for (Point p : original_points) {
        ost << '(' << p.x << ',' << p.y << ')' << endl;
    }
    ost.close();
    ifstream ist{name};
    if (!ist) error("can't open input file", name);
    vector<Point> processed_points;
    for (Point p; ist >> p;) {
        processed_points.push_back(p);
    }
    cout << endl;
    cout << "These are the points read from the file: " << endl;
    for (int i=1; i <= processed_points.size(); i++) {
        cout << processed_points[i] << endl;
    }
}

int main()
{
    f();
    return 0;
}

您輸出括號和逗號,但不使用它們,因此您的第一次讀取操作將失敗。 嘗試:

istream& operator>>(istream& is, Point& p)
{
    char open;
    char close;
    char comma;
    is >> open >> p.x >> comma >> p.y >> close;
    if (open != '(' || close != ')' || comma != ',')
    {
      is.setstate(std::ios_base::failbit);
    }
    return is;
}

由於超出向量的邊界,您的程序最終也會崩潰,您使用的索引從1length ,向量是 0 索引的,因此應該從0訪問到length-1

for (int i = 0; i < processed_points.size(); i++) {
    cout << processed_points[i] << endl;
}

或者只使用基於范圍的循環:

for (auto& point : processed_points) {
    cout << point  << endl;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM