Home > front end >  Printing out specific length in vector array
Printing out specific length in vector array

Time:10-28

I am trying to created a random password from the input text. minimum length is 3. I found out that the first word which is The has size of 6 somehow. Only the first word gives me weird size so far. Eventually, I want to erase when words are less than 3 words. I don't know why it returns size 6. Please advise.

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 file is below.

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

CodePudding user response:

First, in your input text file, there is Byte Order Mark, so it affects the size of the word. Delete that.

In your setMinLength(std::vector<std::string> &words) function.

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
        }
    }
}

Note if you use erase(): when you use erase(), words[i] is now the next word, then the loop increment i and you skip one word. Remember to --i at the end.

  • Related