g++中的分段错误和从文件中读取

Segmentation Fault in g++ and reading from files

本文关键字:文件 读取 错误 分段 g++      更新时间:2023-10-16

我对这个程序有问题,它从两个文件中读取。每个文件A和B的顶部都包含一个int,它是它所拥有的字符串数。程序必须做一个B-a操作,文件a有两个字符串,"两个"answers"三个"。文件B有4个字符串,"一"、"二"、"三"answers"四"。因此,第三个文件中的结果必须是"一"answers"四"。那些不在文件A中,但在文件B中是的。

首先我读取每个文件的大小,然后读取每个文件中的字符串。我计算结果文件的大小,并比较两个文件的字符串。

我使用了gdb调试器,它说问题出在比较文件的for中。我所做的是:如果在A中找不到B中的字符串,我将其放入结果中。

我在这里写了整个程序(不太大),这样你就可以有更好的想法。

非常感谢和抱歉变量中的西班牙语名称。

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

int main(){
int contador = 0;
string* datosA;
string* datosB;
string* resultado;
int tamA, tamB, tamResultado;
ifstream fichA("fA.txt");
if(fichA){
    fichA>> tamA;
    datosA = new string [tamA];
    for(int i = 0; i < tamA; i++){
        fichA>> datosA[i];
    }
    fichA.close();
}

ifstream fichB("fB.txt");
if(fichB){
    fichB>> tamB;
    datosB = new string [tamB];
    for(int i = 0; i < tamB; i++){
        fichB>> datosB[i];
    }
    fichB.close();
}

tamResultado = tamB - tamA;
resultado = new string [tamResultado];

contador = 0;
for(int i = 0; i < tamB; i++){
    bool enc = true;
    for(int j = 0; j < tamA && enc; j++){
        if(datosB[i] != datosA[j]){
            enc = false;
        }
    }
    if(!enc){
        resultado[contador] = datosB[i];
        contador++;
    }
}
delete[] datosA;
delete[] datosB;

ofstream fout("resultado.txt");
if(fout){
    for(int i = 0; i < tamResultado; i++){
        fout<< resultado[i];
    }
    fout.close();
}
delete[] resultado;
datosA = datosB = resultado = 0;
return 0;   
}

检查您的条件。

每当你遇到不同的元素时,你就会改变你的旗帜。但是,只有当阵列A中的所有元素与阵列B中的元素在特定位置不同时,才应该发生这种情况。

按照现在的编写方式,您正试图将数组B中的所有四个元素添加到生成的数组中,这是分段错误,因为您正试图访问未分配的内存。

一种可能的解决方案是添加计数器,该计数器检查阵列A中的两个元素是否与阵列B中的元素不同。

类似这样的东西:

for(int i = 0; i < tamB; i++){
    bool enc = true;
    // counter that keeps track of number of different elements
    int count = 0;
    for(int j = 0; j < tamA && enc; j++){
        if(datosB[i] != datosA[j]){
            count++;
        }
    }
    // check if all elements in datosA are different than datosB[i]
    if(count == tamA){  
        resultado[contador] = datosB[i];
        contador++;
    } }

这应该按预期进行。