分段错误:11(C++文件输入和输出、类和动态数组)

Segmentation fault: 11 (C++ File input and output, classes and dynamic arrays)

本文关键字:输出 动态 数组 输入 错误 文件 C++ 分段      更新时间:2023-10-16

我正在开发一个程序,该程序应该读取文件,将其内容作为输入并将其写入动态数组。每次我执行程序输出(打印输出)应该作为输入的单词时,我都会得到"分割错误:11"。该程序的概念是读取包含英语单词的文件及其西班牙语翻译和打印输出。原始代码更大,但我只包含触发段错误的文件 I/O 和动态数组。任何关于为什么会发生这种情况的帮助和可能的修复,将不胜感激。

我的代码:

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
class diccionario {
public:
    void abrir_file (ifstream& entrada, ofstream& salida);
    diccionario();
    ~diccionario();
    void escribir(ofstream& salida);
    void validar();
private:
    string *espdic;
    string *engdic;
    int size;
};
diccionario::diccionario () : cantidad(0), size(10) {
    string *espdic = new string [size];
    string *engdic = new string [size];
}
diccionario::~diccionario () {
}
void abrir_file (ifstream& entrada, ofstream& salida) {
  entrada.open ("palabras.txt");
  if(entrada.fail())
    {
      cout << "Error abriendo archivo" << endl;
      salida << "Error abriendo archivo" << endl;
      exit(1);
    }
  salida.open ("salida.txt");
  if(salida.fail())
    {
      cout << "Error abriendo archivo" << endl;
      salida << "Error abriendo archivo" << endl;
      exit(1);
    }   
}
int main() {
    int opcion, size;
    ifstream entrada;
    ofstream salida;
    string temp;
    diccionario english;
    string *espdic = new string [size];
    string *engdic = new string [size];
    abrir_file (entrada, salida);
    if(entrada.is_open()) {
        while(entrada >> temp) {
            engdic[size] = temp;
            size++;
        }
    }
    do {
        menu(salida);
        cin >> opcion;
        switch (opcion) {
            case 1:
            english.escribir(salida);
            break;
            case 2:
            cout << "Fin de programa" << endl;
            salida << "Fin de programa" << endl;
            exit(1);
        }
    } while (opcion != 0);
    salida.close();
    entrada.close();
    return 0;
}

输入文件(帕拉布拉斯.txt):

God Dios
Violet Violeta
Ray Rayo
Master Maestro
Power Poder

我在这里看到的问题很少。

  1. size未提供。

在主功能中。您声明了大小变量,但从未为其提供值。假设您需要为 25 个元素分配。用作

int size=25;
  1. 访问越界的东西。

    工程[大小] = 温度;

假设 engdic 的

分配是针对 25 个元素的,其索引从 0 开始并以 24 结束(engdic[0] 到 engdic[24]),但是,在上述语句大小未初始化的情况下,它可能访问超过 24 个,从而导致分段错误。

  1. size循环之前while未初始化为零。

在下面的代码中,大小的起始值和结束值是什么?理想情况下,您应该从 0 开始,以最大容量结束(此处为 24)

while(entrada>> temp) { 工程[大小] = 温度; 大小++;}