c++ file search database file and cout next line -
i have 2 codes here, first 1 here prompts number, tells on line number in text file "example.txt"
#include <string> #include <vector> #include <iostream> #include <fstream> using namespace std; int main() { string s; vector <string> v; ifstream fileinput; int qwe = 0; fileinput.open("example.txt"); while (getline( fileinput, s )) { v.push_back( s ); } cout << "number: " << endl; cin >> qwe; cout << "line " << qwe << ": " << v[ qwe ] << endl; fileinput.close(); }
and second code here prompts user input adds "?" @ beginning because it's algorithm in future, used then. searches in text file , gives user line number of user inputted
#include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <sstream> #include <string> using namespace std; int main() { ifstream fileinput; int offset; string line; string search; cout << "hi" << endl; getline(cin, search); search = "?" + search; // open file search fileinput.open("example.txt"); if(fileinput.is_open()) { while(getline(fileinput, line)) { for(unsigned int curline = 2; getline(fileinput, line); curline++) { if (line.find(search) != string::npos) { cout << "found: " << search << " line: " << curline << endl; } } } fileinput.close(); } else cout << "unable open file."; }
so problem need sort of combine these codes, need prompts user input , figures out line number, , couts next line, how do this?
like do:
#include <fstream> #include <algorithm> #include <iostream> int main() { std::string input; std::cout<<"enter line search for: \n"; std::getline(std::cin, input); std::fstream file("example.txt", std::ios::in); if (file.is_open()) { std::string line; int line_count = 0; while(std::getline(file, line)) { if (line.find(input) != std::string::npos) { std::cout<<"the line found was: \""<<line<<"\" @ line: "<<line_count<<"\n"; if (std::getline(file, line)) { std::cout<<"the line after is: \""<<line<<"\"\n"; ++line_count; } else { std::cout<<"there no lines after that!\n"; } } ++line_count; } file.close(); } }
with example file of:
hello world testing finding lines
you can search "hello" , return line 0 aka first line..
however, if turn on find_approximate_line
, searched "hey world", still return line 0 because of hammingdistance
algorithm.
if don't care partial/close matches can remove hammingdistance algorithm , keep using std::string.find
.
one example output is:
enter line search for: > hello world line found was: "hello world" @ line: 0 line after is: "i testing"
Comments
Post a Comment