how do I use ' string::find ' to find a word in file using C++

16.5k Views Asked by At

I'm creating a program that will open a file and search for a desired word within the text. I created the following word bank...

Lawyer    
Smith Janes
Doctor    
Michael Zane
Teacher   
Maria Omaha



#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <sstream>   
using namespace std;   

int main ()    
{    
    // Declarations    
    string reply;    
    string inputFileName;    
    ifstream inputFile;    
    char character;

    cout << "Input file name: ";    
    getline(cin, inputFileName);

    // Open the input file.    
    inputFile.open(inputFileName.c_str());      

   // Check the file opened successfully.    
    if ( ! inputFile.is_open())
    {   
                  cout << "Unable to open input file." << endl;    
                  cout << "Press enter to continue...";    
                  getline(cin, reply);           
                  return 1;
    }

Now that I save the whole file into a string how could I search inside that string for a specific word I'm looking for...

I'm learning C++ from this Website http://www.cprogramming.com/tutorial/lesson10.html

I think you use string::find but I couldn't find much reference on how to search beside this wesite..

http://www.cplusplus.com/reference/string/string/find/

This section will display the whole file.

    string original;
    getline(inputFile, original, '\0');
    cout << original << endl;    
    cout << "\nEnd of file reached\n" << endl;

    // Close the input file stream   
    inputFile.close();    
    cout << "Press enter to continue...";    
    return 0;      
}

This is how I think the program should act...

Please enter a word: Smith Janes
Smith Janes Lawyer

 another example.... 

Please enter a word: Doctor 
Michael Zane Doctor
3

There are 3 best solutions below

0
On

find returns the position (zero based offset) in the string where the word is found. If the word is not found it returns npos.

#include <string>
#include <iostream>

int main()
{
    std::string haystack("some string with words in it");

    std::string::size_type pos = haystack.find("words");
    if(pos != std::string::npos)
    {
        std::cout << "found \"words\" at position " << pos << std::endl;
    }
    else
    {
        std::cout << "\"words\" not found" << std::endl;
    }
}
6
On
#include <string>
#include <iostream>
#include <cstdlib>

int main() {
  std::string haystack = "Lawyer\nSmith Janes\nDoctor\nMichael Zane\nTeacher\nMaria Omaha\n";

  std::string needle = "Janes";

  auto res = haystack.find(needle);
  if (std::string::npos == res) {
    std::cout << "Not found\n";
    std::exit(EXIT_FAILURE);
  }
  std::cout << res << '\n';
}

res is an index into the string at the point where "Janes" is (Should be 13).

The functionality you appear to be asking for is more complex than just finding some content in a string. The output you show has a user input either a name or a profession and the output is the related profession or name.

It's simple to write a program that shows the line the 'needle' is on, or to show always show the previous line, or always show the next line. But what you're asking for is to show one or the other depending on what was searched for.

One simple way we could implement this is to find if the needle is on an even or odd line and base what we show on that.

First we get the line number.

auto line_num = std::count(std::begin(haystack), std::begin(haystack) + res, '\n');

Based on the content you showed, professions are on even lines and names are on odd lines. We can easily get the line numbers we want:

auto profession_line_num = line_num/2*2;
auto name_line_num = line_num/2*2 + 1;

Next, we can split the text up into lines since we need to work with whole lines and get lines by index. The method I show below makes a copy of the text and is inefficient, but it's easy.

Here's a split function:

std::vector<std::string> split(std::string const &s, std::string const &delims) {
    std::vector<std::string> res;

    std::string::size_type i = 0;
    auto found = s.find_first_of(delims, i);
    while (std::string::npos != found) {
        res.emplace_back(s, i, found-i);
        i = found+1;
        found = s.find_first_of(delims, i);
    }
    res.emplace_back(s, i);

    return res;
}

And we use the split function like so:

auto lines = split(haystack, '\n');

Now, we can show the lines we want.

std::cout << lines[name_line_num] << ' ' << lines[profession_line_num] << '\n';

Which once you put the program together prints:

Smith Janes Lawyer
3
On

I think this has all the information you need.

http://www.cplusplus.com/reference/string/string/find/