分段错误:11(C++文件输入和输出、类和动态数组)
Segmentation fault: 11 (C++ File input and output, classes and dynamic arrays)
我正在开发一个程序,该程序应该读取文件,将其内容作为输入并将其写入动态数组。每次我执行程序输出(打印输出)应该作为输入的单词时,我都会得到"分割错误: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
我在这里看到的问题很少。
-
size
未提供。
在主功能中。您声明了大小变量,但从未为其提供值。假设您需要为 25 个元素分配。用作
int size=25;
访问越界的东西。
工程[大小] = 温度;
分配是针对 25 个元素的,其索引从 0 开始并以 24 结束(engdic[0] 到 engdic[24]),但是,在上述语句大小未初始化的情况下,它可能访问超过 24 个,从而导致分段错误。
-
size
循环之前while
未初始化为零。
在下面的代码中,大小的起始值和结束值是什么?理想情况下,您应该从 0 开始,以最大容量结束(此处为 24)
while(entrada>> temp) { 工程[大小] = 温度; 大小++;}
相关文章:
- 输出没有重复元素的动态数组(收缩数组)C++
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- 这种动态调整数组大小的尝试的输出有什么问题
- 动态分配的数组在输出时丢失 ifstream 数据
- 动态分配的输入,并在C 中输出2D阵列
- 创建一个动态数组,包括汽车的年份和品牌,但无法保存我的第一个输出
- 假设动态范围,以下C++程序的输出是什么
- 在泰勒级数展开中动态表示负输出 --> C++
- 从函数指针输出动态数组
- 使用指针动态数组同时输出整数值列表
- 分段错误:11(C++文件输入和输出、类和动态数组)
- 如何在神经网络中动态设置输入/输出的数量和行为
- 动态初始化的 2D 数组输出错误
- 如何在c++中从容器数组中输出动态数组值
- 动态更改输出项的数量
- 创建动态循环队列,元素输出正常,但程序崩溃
- 在c++中打印动态创建的负数会导致不正确的输出
- 将.txt文件中的字符串输出到成员方法局部作用域之外的动态数组
- 输出动态数组或矩阵的元素