在C++中比较来自向量的字符串时出现分段错误
Segmentation Fault when comparing strings from vectors in C++
我的代码如下所示。这些单词是从两个文件中读入的,需要检查以查看两个文件中是否出现了单词。在它匹配两个单词中的第一个单词并将其添加到新向量后,我不断收到 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
。因此,如果向量中有一个元素,您将尝试访问两个元素。您需要将两个<=
比较更改为<
.
相关文章:
- C++函数的字符串错误"find_first_of"
- 流字符串错误输出
- 在图像上覆盖文本的程序会产生无休止的字符串错误
- 字符串错误的向量
- C++字数统计程序使用C字符串错误在程序运行后
- 从函数返回字符串C++错误
- 字符串错误或编译器错误
- SQL 字符串错误?没有这样的列
- C/C++ 字符串错误与 ARM SEG 故障总线错误
- 字符串错误输出
- C++调用堆上的类(空字符串错误)
- 运行时字符串错误C++
- 字符串递归函数中的字符串错误
- 从文本文件/文本流中读取Q字符串错误
- 动态内存c++程序中的字符串错误
- 发现c++正则表达式子字符串错误模式
- 在Cocos2d-x中比较字符串错误
- c++读TXT到字符串错误
- 字符串错误检查
- Chromium嵌入式框架VS2013字符串错误