0

I am creating a little dictionary.I have created a vector of strings to print some words beforehand to take one of those as input from user and describing the word to them.

I have tried googling about it and tried to set unsigned int i = 0 in the for loop.

The part of the code that does so is given below:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<string> word = {"none", "jump fatigue" , "scrim game", "box up", "turtling", "swing", "flickshot", "tracking", "panic build", "cone jump", "ttv", "one-shot", "tagged", "blue", "white", "lasered", "melted", "default", "bot", "stealth", "aggresive", "sweaty", "tryhard", "choke"};
    for(int i = 0; i <= word.size(); i++){
        cout<<i<<")"<< word[i] << endl;
    }
    return 0;
}

It prints without any error and at the end of running the code it freezes for while and ends with, Process terminated with status -1073741819(0 minute(s), 4 second(s)) whereas it's supposed to terminate with 0

While debugging the code I get warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

  • 1
    `i <=` should be `i <`, your last loop iteration reads past the end of the vector. Or even better, use a range-based for loop to avoid that kind of mistake. –  Jun 07 '19 at 04:37
  • ^^ Also: https://stackoverflow.com/questions/7443222/how-do-i-deal-with-signed-unsigned-mismatch-warnings-c4018 – Bob__ Jun 07 '19 at 04:40

1 Answers1

1

Your problem is in your for loop i <= word.size(). This should be <. The last index will be one less than the size, since the first index is 0.

I'd recommend at least using size_t in the for loop to get a better type

for (std::size_t i = 0; i < word.size(); i++) {

though a cleaner way to iterate would be a range-based for loop

for (auto& w : word) {
    std::cout << w << '\n';
}
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174