我正在接受这样的用户输入:
algo_type "pattern" filename
例如。
bf "inging" input_file.txt
到目前为止,我将用户输入分为三个不同的变量,一个用于算法类型,一个用于我正在寻找的模式,一个用于文件名。一旦我得到模式和文件名,我就会尝试将模式带入 Bruteforce 算法并搜索每一行并打印模式在 .txt 文件行中出现的位置。现在,尽管每次我将输入输入到算法中时,它都会返回 -1,这意味着 BruteForce 没有运行?我到底做错了什么?
int BruteForce(const string& line, const string& pattern){
int n , m;
n = line.length();
m = pattern.length();
for(int i = 0 ; i < n - m ; i++){
int j = 0;
while( j < m && line[i + j] == pattern[j]){
j = j+1;
if( j == m){
return i;
}
}
}
return -1;
}
int main(){
string text, algo_type , pattern , fname, line;
getline(cin ,text);
istringstream iss(text);
if(iss >> algo_type >> pattern >> fname){
cout << algo_type << pattern << fname << "'\n'";
}
int i = 0;
ifstream ifs;
ifs.open(fname.c_str());
while(getline(ifs, line) && fname != ""){
if( algo_type == "bf"){
cout << "Line " << i++ << ":" << BruteForce(line,pattern) << endl;
}
}
return 0;
}
最佳答案
我想你想要 return -1
在 BruteForce 结束时,而不是在第一次迭代结束时。
另外,第一个循环条件需要有<=
而不是 <
, 否则将找不到以该位置结尾的匹配项。
这是一个完整的、固定的版本:编辑根据编辑,在行内列出多个匹配项:
#include <string>
using namespace std;
int BruteForce(const string& line, size_t start, const string& pattern) {
const size_t n = line.length();
const size_t m = pattern.length();
if (n<m) return -1;
for(size_t i = start; i <= (n - m); i++) {
for(size_t j=0; j < m && (line[i + j] == pattern[j]); ++j) {
if(j == m-1) {
return i;
}
}
}
return -1;
}
#include <iostream>
#include <fstream>
#include <sstream>
int main() {
string text, algo_type, pattern, fname, line;
getline(cin ,text);
istringstream iss(text);
if(iss >> algo_type >> pattern >> fname) {
cout << " " << algo_type << " " << pattern << " " <<fname << "\n";
}
int i = 1;
ifstream ifs;
ifs.open(fname.c_str());
while(getline(ifs, line) && fname != "") {
if(algo_type == "bf") {
int pos = -1;
while (-1 != (pos = BruteForce(line, pos+1, pattern)))
cout << "Line " << i << ":" << pos << " " << line << endl;
}
i++;
}
return 0;
}
在 Coliru 上观看直播: http://coliru.stacked-crooked.com/a/f1a7693d7d3bd7c5
我测试过
./test <<< "bf iss /etc/dictionaries-common/words" | grep Miss
打印出来
Line 10241:1 Miss
Line 10242:1 Mississauga
Line 10242:4 Mississauga
Line 10243:1 Mississippi
Line 10243:4 Mississippi
Line 10244:1 Mississippi's
Line 10244:4 Mississippi's
Line 10245:1 Mississippian
Line 10245:4 Mississippian
Line 10246:1 Mississippian's
Line 10246:4 Mississippian's
Line 10247:1 Mississippians
Line 10247:4 Mississippians
Line 10248:1 Missouri
Line 10249:1 Missouri's
Line 10250:1 Missourian
Line 10251:1 Missourian's
Line 10252:1 Missourians
Line 10253:1 Missy
Line 10254:1 Missy's
关于c++ - 运行 Brute Force 算法时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18687197/