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