2017-06-18 25 views
-2

基本的に実装したいのは、テキストファイルがあり、特定の単語を場所(行の位置とその単語の場所ライン)。それはC++の基本的な知識を使用して実装することができる方法...私は初心者だと研究ベクトルetc.Thanksを持っていないあなたの助け各単語を1行に繰り返します(文字列)。C++

fstream x; 
x.open("file.txt); 
while(getline(x,str)) { 
    //extract word from str and save in str1 
    if(reqWord == str1) 
     print("match found"); 
}` 
+1

で正規表現を使用していますか?単語のマッチング?行番号を決定しますか?行の位置を決定する?読み込まれた行の数を維持しながら、行ごとにテキストを読み上げました。 'string :: find()'を使って各行をチェックし、それは文字列の開始位置も返します。 – twain249

+0

行の位置とともに行の中の単語を見つけるには...行の位置は簡単にわかりますが...行内の単語の位置を見つける –

答えて

1

これは高度なトリックの一種ですが、私はあなたがしようと提案しますstringstream

std::stringstream ss; 
ss << str; 

while(ss >> str1) 
    ... 
+0

はい、残念ながら私の先生はそれを受け入れません! –

1

あなたは検索語の特定の発生を検索するために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; 
} 
+0

ありがとうございます:) –

+0

これは、OPが要求したとおりの単語だけを検索するのではなく、サブストリングに一致します。 – zett42

+1

@ zett42が指摘している問題に対処するための回答を編集しました –

関連する問題