c++fstreamcoredumpfloating-point-exceptions

(C++) I am trying to read and output a random line from a text file and I keep getting "Floating Point Exception (Core Dumped)" when running it


Basically what the title says. I'm trying to write code that will take in a random word from a file called "words.txt" and output it. I run it and keep getting the error "Floating Point Exception (Core Dumped)".

Here's the code:

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

using namespace std;

int main ()
{
  vector<string> word;
  fstream file;
  file.open("words.txt");
  cout << word[rand()% word.size()]<<endl;
 return 0;
}

And here's "words.txt"

duck
goose
red
green
phone
cool
beans

Thanks guys!


Solution

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