【问题标题】:Printing out specific length in vector array打印出向量数组中的特定长度
【发布时间】:2021-12-13 06:03:59
【问题描述】:

我正在尝试从输入文本中创建一个随机密码。 最小长度为 3。我发现第一个单词 The 的大小为 6。 到目前为止,只有第一个词给了我奇怪的大小。 最终,当单词少于 3 个单词时,我想擦除。 我不知道为什么它返回大小 6。 请指教。

void setMinLength(std::vector<std::string> &words) {

    for (int i = 0; i < words.size()-1; i++) {
        if (words[i].size() == 6) {
            std::cout << words[i] << std::endl;
            //words.erase(words.begin() + i);
        }
    }
}

int main() {

    std::ifstream myFile("input.txt");
    if (!myFile.is_open()) { 
       std::cout << "Couldn't open the file."; 
       return 0;   
    }

    std::vector<std::string> words;
    std::string word;

    while (myFile >> word) {
        words.push_back(word);
    }

    setMinLength(words);
    myFile.close();
    return 0;
}

Input.text 文件在下面。

The Project Gutenberg EBook of Grimms’ Fairy Tales, by The Brothers Grimm This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or


The
Tales,
anyone
almost
re-use
online
Title:
Taylor
Marian

hex editor

【问题讨论】:

  • if (!myFile.is_open()) { std::cout &lt;&lt; "Couldn't open the file."; } -- 即使文件无法打开,您的程序也会继续处理数据。
  • 如果只有第一个单词的大小不寻常,可能您的文件有字节顺序标记。在十六进制编辑器中打开它并检查。请注意,它之前似乎已经打印了一个换行符。
  • void setMinLength(std::vector&lt;std::string&gt; words) -- 此外,即使您注释掉了 erase 行,该行也不会对 main 中的向量产生任何影响,因为您将向量传递给价值。
  • 还要考虑在迭代矢量时从矢量中擦除的效果。
  • 我在十六进制编辑器的第一个 The 之前看到了一些东西。我该怎么办?

标签: c++ vector


【解决方案1】:

首先,在您的输入文本文件中,有字节顺序标记,因此它会影响单词的大小。删除那个。

在您的 setMinLength(std::vector&lt;std::string&gt; &amp;words) 函数中。

void setMinLength(std::vector<std::string> &words) {

    for (int i = 0; i < words.size()-1; i++) {
        if (words[i].size() == 6) {
            std::cout << words[i] << std::endl;
            //words.erase(words.begin() + i);
            // --i; explain below
        }
    }
}

注意如果你使用erase():当你使用erase()时,words[i]现在是下一个单词,然后循环增加i并且你跳过一个单词。最后记得--i

【讨论】:

  • 嗨,如果我不能删除这个词,因为这是一个给定的文本,该怎么办?如果不删除第一个单词就无法获得正确的尺寸,我应该和给我这个的人谈谈吗?
  • @parapara 是的,你应该这样做。
  • 感谢您的建议。我应该考虑一下 --i 的东西。
猜你喜欢
  • 2022-01-18
  • 2020-01-20
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多