【问题标题】:Segmentation Fault when comparing strings from vectors in C++在 C++ 中比较来自向量的字符串时出现分段错误
【发布时间】:2018-10-08 04:37:52
【问题描述】:

我的代码如下所示。单词是从两个文件中读入的,需要检查是否在两个文件中都出现了单词。在它与两者中的第一个单词匹配并将其添加到新向量后,我不断收到段错误。我之前添加了 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]);
             }
        }
    }

【问题讨论】:

    标签: c++ vector segmentation-fault string-comparison


    【解决方案1】:

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

    【讨论】:

    • 或者使用foreach循环:for(const auto&amp; lhs : sizeOneWord)
    • @JamesPicone 只是为了完整性,您可能是指for (const auto&amp; s: wordOne);
    • 我尝试更改顶部的比较,但这并没有改变任何东西。当我之前检查它们时,尺寸是正确的。我对整数使用了基本相同的代码,它工作得很好,所以我很困惑为什么字符串不能以同样的方式工作。
    • @Tas 哎呀!是的,我愿意。
    • @user2217 读取向量的“结束”(这段代码正在执行的操作)是“未定义的行为”,未定义的行为可以做任何它想做的事情,包括“看起来可以工作” .实际上,字符串是一个复杂的对象,而 int 不是,因此被解释为字符串的内存可能不满足字符串如何运行并导致分段错误的一些内部要求。
    猜你喜欢
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 2014-10-23
    • 2015-09-28
    相关资源
    最近更新 更多