0

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
Cris
  • 128
  • 3
  • 4
  • 17
  • What's the question exactly? – Borgleader Aug 06 '13 at 21:22
  • @Borgleader I'm searching a word in my file that will display their occupation. The occupations are listed on the top along with their name on the bottom. – Cris Aug 06 '13 at 21:29
  • That's not a question, that's a description of what you're trying to do. I'm asking you what's wrong with it? – Borgleader Aug 06 '13 at 21:30
  • @Borgleader oh sorry... There's nothing wrong with my code but I looking for help on how to use [string::find] to implement in my code so I could search a word in my file. – Cris Aug 06 '13 at 21:31

3 Answers3

1

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;
    }
}
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
1
#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
bames53
  • 86,085
  • 15
  • 179
  • 244
  • Thanks for the help. Lets say I have two string with both different things. How could I search in both string for a word? ' string namelist; ' ' string namemembers; ' search for Michael in string namemembers and namelist – Cris Aug 07 '13 at 03:25
  • 1
    @Cris Given an operation that searches a single string (e.g. `haystack.find(needle)`) there's a very simple algorithm for searching two, three, or any number of strings; In pseudo-code it's `for (each string) { search the string }`. – bames53 Aug 07 '13 at 15:58
  • Thanks for the comment is just that I didn't understood what " ::npos " meant so I wasn't really clear on how to use it. Is is necessary to use " npos " in order to search for a word in a string ? Because I've been playing with the code it looks it doesn't. – Cris Aug 07 '13 at 18:48
  • As described in the [`std::string::find` documentation](http://en.cppreference.com/w/cpp/string/basic_string/find) `npos` is a special index value returned to indicate that the substring was not found, among other things. In the pseudo-code I showed earlier you have to include what to do with the found substring and what to do if the substring is not found, as part of the `{ search the string }`. – bames53 Aug 07 '13 at 19:05
  • @Cris So actual code might look like (in C++11): `std::string haystacks[] = {"aa","ab","ac","xx"}; std::string needle = "a"; for (auto haystack : haystacks) { auto res = s.find(heedle); if (std::string::npos == res) { std::cout << "NOT FOUND!\n"; } else { std::cout << "found\n"; } }` – bames53 Aug 07 '13 at 19:06
  • Thanks for breaking the code for me is just that I'm a beginner...Thanks for your patience. – Cris Aug 08 '13 at 00:56
-1

I think this has all the information you need.

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

MasterPlanMan
  • 992
  • 7
  • 14
  • I don't think if you notice but I already posted that site because it has absolutely no information relevant... – Cris Aug 06 '13 at 21:54
  • @Cris how is that information is not relevant? That website tells you what `std::string::find` does and tells you what parameters you can send it. It even gives examples on what it returns with given inputs. I think that maybe you should replace `getline(inputFile, original, '\0')` with just `getline(inputFile, original)`, then re-format your input file so that name and occupation are on the same line, and each person is on a separate line. Then, go through the file line by line and if you find the input text in a line (`original`), output that line – wlyles Aug 06 '13 at 23:04
  • responses that are nothing more than a link belong as comments, not answers. – Ben Barden Sep 23 '14 at 20:58