Guest User

Untitled

a guest
Jun 30th, 2020
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <random>
  4. #include <string>
  5. #include <vector>
  6.  
  7. int inputmozi = 0;
  8. char buffer[256];
  9.  
  10. /* fileで指定されたテキストファイル内の文字列の中から
  11.    wordを含む文字列を返す。
  12.    複数ある場合、そのうちいずれかを乱数を用いて返す。
  13.    存在しない場合/ファイルオープン失敗の場合、空文字列を返す。
  14. */
  15. std::string find_word(const std::string& file, const std::string& word) {
  16.     std::string result;
  17.     std::ifstream stream(file);
  18.     if (stream.is_open()) {
  19.         std::vector<std::string> lines;
  20.         std::string line;
  21.         // wordを含む文字列の集合をlinesに求める
  22.         while (std::getline(stream, line)) {
  23.             if (line.find(word) != std::string::npos) {
  24.                 lines.push_back(line);
  25.             }
  26.         }
  27.         // linesが空でなければ、そのうちいずれかをデタラメに返す
  28.         if (!lines.empty()) {
  29.             std::random_device gen;
  30.             std::uniform_int_distribution<int> dist(0, lines.size() - 1);
  31.             result = lines.at(dist(gen));
  32.         }
  33.     }
  34.     return result;
  35. }
  36.  
  37. int main() {
  38.     //  キーボード入力待ち
  39.     inputmozi = getchar();
  40.     unsigned char buffer;
  41.     // 数値から文字への変換
  42.     buffer = (char)inputmozi;
  43.     std::string word = buffer;
  44.     for (int i = 0; i < 10; ++i) {
  45.         std::string result = find_word("d.txt", word);
  46.         if (!result.empty()) {
  47.             std::cout << word << " -> " << result << std::endl;
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment