C ++我正在尝试从文本文件读取和输出随机行,并且在运行它时不断收到“浮点异常核心已转储”

问题描述

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

这是代码

# Rewrite any request for a static resource that does not exist (in the root)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule \.\w{2,4}$ quotes%{REQUEST_URI} [L]

这是“ 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;
}

谢谢大家!

解决方法

您只是打开文件而没有阅读。 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;
}