在C++中比较来自向量的字符串时出现分段错误

Segmentation Fault when comparing strings from vectors in C++

本文关键字:字符串 错误 分段 向量 C++ 比较      更新时间:2023-10-16

我的代码如下所示。这些单词是从两个文件中读入的,需要检查以查看两个文件中是否出现了单词。在它匹配两个单词中的第一个单词并将其添加到新向量后,我不断收到 seg 错误。我之前添加了 print 语句,它在遇到 seg 错误之前一直使用 int n 参数运行循环。我对C++相当陌生,所以最好是最基本的帮助方式。

#include <iostream>
#include <string>
#include <fstream>
#include <locale>
#include <vector>
using namespace std;
vector<string> wordOne;
vector<string> wordTwo;
fileOne.open(argv[2]);
fileTwo.open(argv[3]);
while (fileOne >> wordsFirstFile) {
wordOne.push_back(wordsFirstFile);
}
while (fileTwo >> wordsSecondFile) {
wordTwo.push_back(wordsSecondFile);
}
fileOne.close();
fileTwo.close();
int sizeOneWord = wordOne.size();
int sizeTwoWord = wordTwo.size();
vector<string> printWords;
int m = 0;
int n = 0;
for (m = 0; m <= sizeOneWord; m++) {
for (n = 0; n <= sizeTwoWord; n++) {
if (wordOne[m] == wordTwo[n]) {
printWords.push_back(wordOne[m]);
}
}
}

假设sizeOneWord是一个。这意味着只有一个法律索引进入wordOne。但是您的循环将循环两次,一次是m == 0,一次是m == 1。因此,如果向量中有一个元素,您将尝试访问两个元素。您需要将两个<=比较更改为<.