无法写入文件字符指针

unable to write to a file char pointer

本文关键字:字符 指针 文件      更新时间:2023-10-16

我正在写一个指向文件的字符指针,但当我这样做时,我的程序总是在名称上崩溃,我无法弄清楚的原因

#include <iostream>
#include <iomanip>
#include <string>
#include "AmaProduct.h"
using namespace std;
namespace sict{
AmaProduct::AmaProduct(char file){
    fileTag_ = file;
}
const char* AmaProduct::unit()const{
    return unit_;
}
void AmaProduct::unit(const char* value){
    for (int i = 0; i != 9; i++){
        unit_[i] = value[i];
    }
    unit_[11] = 0;
}
fstream& AmaProduct::store(fstream& file, bool addNewLine)const{
    file.open("file.txt");
    if (file.is_open()){
        file << fileTag_ << "," << sku() << ",";
        file<< name() << ",";//here
        file<< price() << "," << taxed() << "," << quantity() << "," << unit_ << "," << qtyNeeded();
        if (addNewLine){
            file << endl;
        }
    }
    file.close();
    return file;
}

头文件

#ifndef SICT_AMAPRODUCT_H__
#define SICT_AMAPRODUCT_H__
#include "Streamable.h"
#include "Product.h"
#include "Date.h"
#include "ErrorMessage.h"
#include "general.h"
#include <iostream>
#include <fstream>
namespace sict{
class AmaProduct : public Product{
private:
  char fileTag_;
  char unit_[11];
protected:
  ErrorMessage err_;
public:
  AmaProduct(char file='N');
  const char* unit()const;
  void unit(const char* value);
  fstream& store(fstream& file, bool addNewLine = true)const;
  fstream& load(std::fstream& file);
  ostream& write(ostream& os, bool linear)const;
  istream& read(istream& is);
};
}

name()

const char* Product::name()const{
    return name_;
}
char* name_;
void Product::name(char* name){
    delete[] name_;
    name_= new char[strlen(name)+1];
    strcpy(name_,name);
}

如果有人对其他文件感兴趣,我也会上传它们。

有几种可能性,但如果cout<<name()导致分段故障,最可能的情况是:

  • name_仍然是nullptr
  • name_是一个无效指针(例如,如果您复制了不遵守3规则的结构)

为了使代码更加可靠,您可以使用string更改所有char*、它们乏味的内存分配和c风格的字符串操作。

如果不这样做,请确保在复制或复制构造结构时遵守3的规则,以避免浅层复制和指针问题,并确保在使用固定大小的char数组时,确保不会溢出缓冲区

还要注意,这样做可能会使缓冲区溢出:

    file.getline(n, ',');
    name(n);

因为当istream::getline()有两个参数时,它将大小(此处为44,逗号的ascii值)作为第二个参数。file.getline(n, 7, ',')将是正确的形式。