-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
62 lines (55 loc) · 1.8 KB
/
main.cpp
File metadata and controls
62 lines (55 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
int main()
{
unordered_map<string, vector<string>> index; // word -> list of files
string folder = "data"; // folder containing text files
// Step 1: Read all .txt files in folder
for (const auto &entry : fs::directory_iterator(folder))
{
if (entry.path().extension() == ".txt")
{
string filename = entry.path().filename().string();
ifstream file(entry.path());
string word;
while (file >> word)
{
// clean punctuation and make lowercase
word.erase(remove_if(word.begin(), word.end(), ::ispunct), word.end());
transform(word.begin(), word.end(), word.begin(), ::tolower);
index[word].push_back(filename);
}
file.close();
}
}
// Step 2: Remove duplicates in the word->file list
for (auto &pair : index)
{
sort(pair.second.begin(), pair.second.end());
pair.second.erase(unique(pair.second.begin(), pair.second.end()), pair.second.end());
}
cout << "✅ Indexed all text files in folder '" << folder << "'\n";
// Step 3: Search loop
string query;
while (true)
{
cout << "\nEnter a word to search (or 'exit' to quit): ";
cin >> query;
transform(query.begin(), query.end(), query.begin(), ::tolower);
if (query == "exit")
break;
if (index.find(query) != index.end())
{
cout << "🔍 Found in files:\n";
for (auto &f : index[query])
cout << " - " << f << "\n";
}
else
{
cout << "❌ No match found.\n";
}
}
return 0;
}