Searching for a word in text file

Hi im trying to write a program that reads in a text file. The user can search for a specific word and it will output another file. The new file will have the line of the word that appeared.
Ex. "Hi my name is Cody.
I'm learning to code and need help."
If the user searches for name the new output file have
"Hi my name is Cody."
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <queue>
#include <iostream>
#include <cstdlib>
#include <random>
#include <chrono>
#include <map>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
using PR = pair<string,string>;

void search(string target){
  int count = 0;
  ifstream in( "text.txt" );
  ofstream output("search.txt");
  vector<PR> v;
  //cout<<"Enter a word to search: "<<endl
//  cin>>target;
  for ( string number, words; in >> number >> words; ) v.push_back( { number, words } );
  for( PR pr : v )
   if(pr.second == target ){
    //output<<pr.first<<pr.second<<endl;
    count++;}

  output<<target<<" appeared "<<count<<" times within this text. "<<endl;
}
int main(){
  search("just");
  return 0;
}

Im having trouble in printing the whole line I'm not sure how to do it. how would i output the whole line?
Last edited on
If I got this right, you open a text file, and search for a word, and when you find it you want to output the entire line that the word is in into another file?

If so, you want to use getline when you take the input in from the file. Otherwise, you'll lose your formatting with ">>". You can keep a vector of string that holds the contents of the whole file, or you can search through the file every time using getline. You'll search through the acquired string for the word (which there are many ways to do, string stream comes to mind), and if it's there, you can output the whole line onto the new file.
Maybe like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>

using namespace std;

bool line_contains_word(const string& line,
                        const string& search_word)
{
  // your search logic here
  return false; // or true
}

int main()
{
  ifstream src("input.txt");
  ofstream dest("output.txt");

  if ((!src) || (!dest))
  {
    perror("Error opening files: ");
    return EXIT_FAILURE;
  }
  string line;
  while(getline(src, line))
    if (line_contains_word(line, "find me"))
      dest << line << '\n';
}
Topic archived. No new replies allowed.