(C++) 我正在尝试从文本文件中读取和输出随机行,并且在 运行 时我一直得到 "Floating Point Exception (Core Dumped)"

(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

基本上就是标题所说的。我正在尝试编写代码,从名为“words.txt”的文件中随机获取一个单词并将其输出。我 运行 它并不断收到错误“浮点异常(核心转储)”。

代码如下:

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

这里是“words.txt”

duck
goose
red
green
phone
cool
beans

谢谢大家!

您刚刚打开了文件,但没有阅读。 word 没有元素,所以 word[rand()% word.size()] 是将某个值除以零。不允许除以零。

您还应该检查文件打开是否成功以及是否确实读取了某些内容。

试试这个:

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

阅读完txt文件中的单词列表,将其保存为向量即可。

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

using namespace std;

int main ()
{
    vector<string> words;
    ifstream file("words.txt");
    string line;
    while (getline(file, line)){
        words.push_back(line); // adds each line of words into vector
    }
cout << words[rand() % words.size()] << endl;
return 0;
}