簡體   English   中英

分段故障讀取文件

[英]Segmentation fault reading file

#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

struct Point
{
    double x;
    double y;
};

istream& operator>>(istream& is, Point& p)
{
    char ch;
    if(is >> ch && ch != '(')
    {
        is.unget();
        is.clear(ios_base::failbit);
        return is;
    }

    char ch2;
    double x;
    double y;

    is >> x >> ch >> y >> ch2;
    if(!is || ch != ';' || ch2 != ')')
    {
        cerr << "Error: Bad record!\n";
        exit(1);
    }
    p.x = x;
    p.y = y; 
}

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

int main()
{
    Point p;
    vector<Point> original_points;
    cout << "Please enter 3 points:\n";
    for(int i = 0; i < 3; ++i)
    {
        cin >> p;
        original_points.push_back(p);
    }

    cout << "\nYou've entered:\n";

    for(Point x : original_points)
        cout << x;

    ofstream ost{"mydata"};
    for(Point x : original_points)
        ost << x;
    ost.close();

    vector<Point> processed_points;
    ifstream ist{"mydata"};
    while(ist >> p)
        processed_points.push_back(p);
    ist.close();

    cout << "original_points: ";
    for(Point x : original_points)
        cout << x;

    cout << "processed_points: ";
    for(Point x : original_points)
        cout << x;

    if(original_points.size() != processed_points.size())
        cout << "Oops! Seems like something went wrong!\n";
    return 0;
}

調試之后,我發現錯誤是由以下代碼行引起的:

while(ist >> p)

這部分代碼幾乎是從書本中復制的:

istream& operator>>(istream& is, Point& p)
{
    char ch;
    if(is >> ch && ch != '(')
    {
        is.unget();
        is.clear(ios_base::failbit);
        return is;
    }

    char ch2;
    double x;
    double y;

    is >> x >> ch >> y >> ch2;
    if(!is || ch != ';' || ch2 != ')')
    {
        cerr << "Error: Bad record!\n";
        exit(1);
    }
    p.x = x;
    p.y = y; 
}

Google和stackoverflow表示此錯誤是由於錯誤地訪問內存引起的。 我花了一個小時檢查此代碼,但無法弄清楚是什么原因引起的。 我今天開始研究流,這是“編程-使用C ++的原理和實踐(第二版)”第10章的練習。

PS對不起,我的英語語法,這不是我的母語)

並不是函數operator>>(istream& is, Point& p)中的代碼的所有分支都導致返回最終值,所以我想您忘記了推返回值return is; 在功能結束時

istream& operator>>(istream& is, Point& p)
{
    char ch;
    if(is >> ch && ch != '(')
    {
        is.unget();
        is.clear(ios_base::failbit);
        return is;
    }

    char ch2;
    double x;
    double y;

    is >> x >> ch >> y >> ch2;
    if(!is || ch != ';' || ch2 != ')')
    {
        cerr << "Error: Bad record!\n";
        exit(1);
    }
    p.x = x;
    p.y = y; 
    return is;
}

暫無
暫無

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

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