g++中的分段错误和从文件中读取
Segmentation Fault in g++ and reading from files
我对这个程序有问题,它从两个文件中读取。每个文件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++;
} }
这应该按预期进行。
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量