Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_DEPRECATE
- #include <iostream>
- #include <fstream>
- #include <random>
- #include <string>
- #include <vector>
- /* fileで指定されたテキストファイル内の文字列の中から
- wordを含む文字列を返す。
- 複数ある場合、そのうちいずれかを乱数を用いて返す。
- 存在しない場合/ファイルオープン失敗の場合、空文字列を返す。
- */
- std::string find_word(const std::string& file, const std::string& word) {
- std::string result;
- std::ifstream stream(file);
- if (stream.is_open()) {
- std::vector<std::string> lines;
- std::string line;
- // wordを含む文字列の集合をlinesに求める
- while (std::getline(stream, line)) {
- if (line.find(word) != std::string::npos) {
- lines.push_back(line);
- }
- }
- // linesが空でなければ、そのうちいずれかをデタラメに返す
- if (!lines.empty()) {
- std::random_device gen;
- std::uniform_int_distribution<int> dist(0, lines.size() - 1);
- result = lines.at(dist(gen));
- }
- }
- return result;
- }
- int main() {
- char word[64];
- scanf("%s", word);
- for (int i = 0; i < 10; ++i) {
- std::string result = find_word("d.txt", word);
- if (!result.empty()) {
- std::cout << word << " -> " << result << std::endl;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement