Advertisement
Guest User

Untitled

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