在C ++中使用向量分割错误?

时间:2019-07-10 15:39:32

标签: c++ vector segmentation-fault

我正在搜索过去3个小时中是否存在已编程到我的代码中的细分错误。当我的函数parseRecord(string)生成一个矢量并且我想打印出其中一个元素时,它基本上就会出现。我将其范围缩小到了这一点,但是找不到错误。向量是Record对象,它们是通过读取文件创建的,该文件每行有一行数据。

我希望有人能帮助我

每当我创建该类的对象(不创建矢量)时,我都可以很好地打印该元素。它仅在我使用创建向量的parseRecord(string)函数时出现。

我也尝试在函数本身中以相同的结果打印它。所以我认为这不是范围问题。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>

#include "record.hpp"

ifstream parsefile(string filename);
std::vector<Record> parseRecord(string line);

int main(int argc, char const *argv[])
{
    std::vector<Record> dataSet = parseRecord("data.dat");

    Record record("D11101001", "Max", "Muestermann",
                  10239, "fictionalmarkt.com", "23.12.19", "11:11:00");

    cout << record;

    for(std::vector<Record>::const_iterator i = dataSet.begin(); i != dataSet.end(); ++i){
        cout << *i << endl;
    }
    return 0;
}

//METHOD-IMPLEMENTATION
//parse-file definition - Test if file is accessible
ifstream parsefile(string filename)
{
    ifstream inFile(filename);
    if (!inFile)
    {
        cerr << "File could not be opened" << endl;
        exit(-1);
    }
    cout << "Input-file is readable!" << endl;
    return inFile;
}

//parse-record definition - read file, add to vector<Record> and return vector
std::vector<Record> parseRecord(string filename)
{
    vector<Record> dataSet;

    ifstream inFile = parsefile(filename);
    string line;

    while (getline(inFile, line))
    {
        stringstream linestream(line);
        string accountNb;
        string firstName;
        string lastName;
        string amountStr; //format 100 = 1.00€
        string merchant;
        string date;
        string time;
        long double amount;

        getline(linestream, accountNb, '|');
        getline(linestream, firstName, '|');
        getline(linestream, lastName, '|');
        getline(linestream, amountStr, '|');
        getline(linestream, merchant, '|');
        getline(linestream, date, '|');
        getline(linestream, time, '\n');

        try
        {
            amount = stold(amountStr);
        }
        catch (const std::exception &e)
        {
            std::cerr << e.what() << '\n'
                      << "Conversion error";
        }

        amount *= 100.0; //to correct the decimal format

        Record recordEntry(accountNb, firstName, lastName, amount, merchant, date, time);

        //cout << recordEntry << endl;

        dataSet.push_back(recordEntry);
    }

    return dataSet;
}

record.hpp

class Record
{
private:
    string accountNb;
    string firstName;
    string lastName;
    long double amount; //format 100 = 1.00€
    string merchant;
    string date;
    string time;
public:
    Record(string, string, string, long double, string, string, string);
    ~Record();
    friend ostream& operator<<(ostream&, const Record&);
};

record.cpp

#include "record.hpp"
#include <ostream>

Record::Record(string accountNb, string firstName, string lastName,
               long double amount, string merchant, string date, string time)
{
    this->accountNb = accountNb;
    this->firstName = firstName;
    this->lastName = lastName;
    this->amount = amount;
    this->merchant = merchant;
    this->date = date;
    this->time = time;
}

Record::~Record()
{
}

ostream &operator<<(ostream &os, const Record &rec)
{
    os << right;
    os << setw(15) << "Account Nb:" << setw(50) << rec.getAccountNb() << endl;
    os << setw(15) << "First Name:" << setw(50) << rec.getFirstName() << endl;
    os << setw(15) << "Last Name:" << setw(50) << rec.getLastName() << endl;
    try
    {
        os << showbase;
        os << setw(15) << "Amount:" << setw(50);
        os.imbue(std::locale("de_DE.UTF-8"));
        os << put_money(rec.getAmount(), true) << endl;
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << "locale not supported system";
    }
    os << setw(15) << "Merchant:" << setw(50) << rec.getMerchant() << endl;
    os << setw(15) << "Date:" << setw(50) << rec.getDate() << endl;
    os << setw(15) << "Time:" << setw(50) << rec.getTime() << endl;
}

结果是控制台打印:

Account Nb:                                         D11101001
First Name:                                               Max
 Last Name:                                       Muestermann
    Amount:                                       102,39 EUR
First Name:                                             Jonny
 Last Name:                                               Doe
    Amount:                                        80,38 EUR
  Merchant:                                          markt.de
      Date:                                          25.12.19
      Time:                                         11:11:19
Segmentation fault (core dumped)

因此它在第一行之后退出。

1 个答案:

答案 0 :(得分:3)

一个错误是您没有从该函数返回值:

ostream &operator<<(ostream &os, const Record &rec)

未从声明返回值的函数返回值是未定义的行为。

ostream &operator<<(ostream &os, const Record &rec)
{
    //...
    return os; // <-- you are missing this line
}

以上是明显的错误,但是对于有效的double,您的测试中还存在另一个潜在错误。您捕获了一个异常,但是当double实际上未初始化时,它的代码就好像double amount; // <--uninitialized. //.. try { amount = stold(amountStr); } catch (const std::exception &e) { std::cerr << e.what() << '\n' << "Conversion error"; } amount *= 100.0; // <-- behavior undefined if exception above this line was thrown. 一样有效。


-- DROP TABLE public."Reports";

CREATE TABLE public."Reports"
(
    "ReportId" integer NOT NULL,
    "ObjectName" text COLLATE pg_catalog."default",
    "PartName" text COLLATE pg_catalog."default",
    "Description" text COLLATE pg_catalog."default",
    "Image" bytea,
    "Date" timestamp with time zone,
    CONSTRAINT "PK_Reports" PRIMARY KEY ("ReportId")
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public."Reports"
    OWNER to postgres;