编写C++程序从Linux命令行搜索索引文件
Writing a C++ Program to Search an Index File From the Linux Command Line
我编写了一个程序,该程序读取数据文件并根据原始文件中的数据创建排序索引文件。然而,我应该写第二个程序,允许用户从Linux命令行搜索这个索引文件。例如,他们应该能够键入
search 12382 prog5.idx
并显示该记录的信息。我不知道如何做到这一点。
我已经写了代码来创建索引文件(作品):
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <iomanip>
using namespace std;
class Record {
string name;
int code;
double cost;
public:
Record() {
}
Record(string tname,int tcode,double tcost) : name(tname),code(tcode),cost(tcost) {
}
friend ostream& operator<< (ostream &os, const Record& r);
};
//print function
ostream& operator<< (ostream &os, const Record& r) {
os << setw(10) << r.name << " " << setw(5) << r.code << " $" << setw(10) << setprecision(2) << fixed << r.cost ;
return os;
}
int main() {
std::map<int, Record> myMap;
ifstream data;
size_t offset_count = 0;
data.open("prog5.dat");
ofstream outFile("prog5.idx", ios::out);
//if file can't be opened, exit
if(!data) {
cerr << "Open Failure" << endl;
exit(1);
}
std::string line;
while (std::getline(data, line)) {
stringstream ss(line);
int key;
string name;
int code;
double cost;
if(ss >> key >> name >> code >> cost) {
Record r(name,code,cost);
myMap.insert( pair<int,Record>(key,r));
}
else {
cout << "Error";
}
}
// print what's stored in map
for(std::map<int,Record>::iterator x = myMap.begin(); x!=myMap.end(); ++x) {
cout << setw(10) << x->first << ": " << x->second << endl;
}
}
并在运行上述代码时获得以下输出:
8: blank 0 $ 0.00
12165: Item16 30 $ 7.69
12345: Item06 45 $ 14.20
12382: Item09 62 $ 41.37
12434: Item04 21 $ 17.30
16541: Item12 21 $ 9.99
21212: Itme31 19 $ 8.35
34186: Item25 18 $ 17.75
41742: Item14 55 $ 12.36
以下是到目前为止我对第二个程序的了解:
#include <prog3.idx>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
if(argc < 3) {
std::cerr << "Too few arguments n";
std::exit(EXIT_FAILURE);
}
int key = atoi(argv[1]);
const char* filename = argv[2];
ifstream input;
input.open("prog5.idx");
}
但我不确定从那里去哪里。有人能帮我吗?
使用映射或多映射并在STL中查找。以索引为键,从剩余数据中生成一个数据类型。程序必须先读取整个文件,然后找到搜索到的索引。
相关文章:
- 如何二进制搜索结构向量并在适当的索引处插入
- 从数组中搜索元素的索引
- 如何使用二叉搜索返回姓氏(给定字符串)的第一个索引/出现次数?
- 如何使该程序在数组中打印搜索字符的索引,否则将找不到它
- 如何使用二叉搜索树的索引生成器解决此问题
- 二叉搜索功能始终返回 -1 值而不是索引
- 使用二叉搜索查找数字的第 N 次出现的索引
- 在Boost多索引容器中搜索位字段数据
- 通过索引快速搜索,并将插入顺序保持在C 中
- 在排序数组 X 中搜索第一个索引 i,使得 X[i] >= a
- O(log n) 索引更新和搜索
- 二进制搜索返回其所属位置的索引
- 在数组 C++ 中搜索字符串索引
- 使用分而治之搜索字符串中'xy'的第一个索引
- C++用于搜索和索引的框架,如 clucene
- 使用 C++ 在文件中进行字符串搜索/索引
- 从搜索算法返回的约定 - 索引或迭代器
- 在二进制搜索期间检查的索引
- C++二进制搜索来查找不动点的索引
- 编写C++程序从Linux命令行搜索索引文件