C++/search
Expert: vijayan - 10/31/2011
QuestionQUESTION: 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/