C++/search

Advertisement


Question
QUESTION: i doesnt display that search word
can you please help me out



#include<iostream>
#include<math.h>
#include <string>
#include <stdlib.h>
#include <cstdlib>
#include <string>
#include <iomanip>
#include<fstream>
#include <iostream>
#include <conio.h>

using namespace std;


int search(){
{
  string SearchID;
        
        cout << "Please enter the search Word ";
        cin >> SearchID;
        
        string parent;
        ifstream Searchfile("documet.txt", ios::in);
        if (Searchfile.is_open())
        {
        bool foundSearchRecord = false;
        while (! Searchfile.eof() )
        {
        string line;
        getline (Searchfile,line);
        if (line.find(SearchID) != string::npos)
        {
        foundSearchRecord = true;
        }
        if (foundSearchRecord == true &&
        line.find("SearchID ") != string::npos)
        {
       
        SearchID = line.substr(line.find('.') + 5);
        break;
        }
        }
        if (!SearchID.empty())
        {
        cout << "The Search word " << SearchID << endl;
      }
      }
      return 0;
}

ANSWER: You need an int main() in every C++ program.

You have included a lot of headers, many of which (conio.h for example) are not standard C++ headers.

Your program should be something like this:

#include<iostream>
#include <string>
#include<fstream>

int main()
{
       std::string SearchID;

       std::cout << "Please enter the search Word ";
       std::cin >> SearchID;

       std::ifstream Searchfile( "documet.txt" ) ;
       std::string line ;
       while( getline (Searchfile,line) )
       {
         if( line.find(SearchID) != std::string::npos )
         {
         // found it
         std::cout << "found in line: " << line << '\n' ;
         }
       }
}


---------- FOLLOW-UP ----------

QUESTION: thank so much vijay for your help
there is only one more issus
it have to display only the text where the search word is
and if iam trying to search 2 words it stuck
lets say:
red apple

or
apple and car
it dont display

Answer
> display only the text where the search word is

std::string::size_type pos = line.find(SearchID) ;
if( pos != std::string::npos )
{
       // pos is the position in the line where SearchID begins
}


> if iam trying to search 2 words    

Use std::getline() to accept a phrase from input.
http://cplusplus.com/reference/string/getline/

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.