あなたは検索語の特定の発生を検索するためにfind
を使用することができます。最初のオカレンスの位置を返します。そうでない場合は、npos
が現在の行にない場合はそれを返します。 実施例の下に見つけてください:
編集 - どの部分をトラブルがある単語の境界
#include <iostream>
#include <fstream>
#include <regex>
int main() {
std::cout << "Please input the file path" << std::endl;
std::string path;
std::cin >> path;
std::ifstream file(path.c_str());
if (file.is_open()) {
std::string search;
std::cout << "Please input the search term" << std::endl;
std::cin >> search;
std::regex rx("\\b" + search + "\\b");
int line_no = 1;
for (std::string line; std::getline(file, line); ++line_no) {
std::smatch m;
if (std::regex_search(line, m, rx)) {
std::cout << "match 1: " << m.str() << '\n';
std::cout << "Word " << search << " found at line: " << line_no << " position: " << m.position() + 1
<< std::endl;
break;
}
}
} else {
std::cerr << "File could not be opened." << std::endl;
return 1;
}
return 0;
}
で正規表現を使用していますか?単語のマッチング?行番号を決定しますか?行の位置を決定する?読み込まれた行の数を維持しながら、行ごとにテキストを読み上げました。 'string :: find()'を使って各行をチェックし、それは文字列の開始位置も返します。 – twain249
行の位置とともに行の中の単語を見つけるには...行の位置は簡単にわかりますが...行内の単語の位置を見つける –