You just opened the file and didn’t read that. word has no elements, so word[rand()% word.size()] is dividing something by zero. Dividing by zero is not allowed.

Also you should check if the opening of file succeeded and something is actually read.

Try this:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>

using namespace std;

int main ()
{
  vector<string> word;
  fstream file;
  file.open("words.txt");
  if (!file) // check if file is opened successfully
  {
    cerr << "file open failed\n";
    return 1;
  }
  for (string s; file >> s; ) word.push_back(s); // read things
  if (word.empty()) // check if something is read
  {
    cerr << "nothing is read\n";
    return 1;
  }
  cout << word[rand()% word.size()]<<endl;
  return 0;
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top