how to search a string from a file in c++?

i am looking for a way or technique by which i can search a string from a text file??

Update:

IN C++ PEOPLE!!!

a way to find a string from a file and store it in a variable so that it can be compared with another string. please help

3 Answers

Relevance
  • Cubbi
    Lv 7
    10 years ago
    Favorite Answer

    To search for a string in a text file you can use, surprise, the C++ command search(). Note that unlike "while (file >> string)" method, which iterates over words, character-based search() will find the string that contains spaces or is adjacent to something non-blank (such as a string in quotation marks)

    #include <iostream>

    #include <fstream>

    #include <iterator>

    #include <string>

    #include <algorithm>

    using namespace std;

    int main()

    {

    ifstream f("test.txt");

    string s("foobar");

    istreambuf_iterator<char> eof;

    if(eof == search(istreambuf_iterator<char>(f), eof, s.begin(), s.end()) )

    cout << "String \"" << s << "\" was NOT found in the file " << endl;

    else

    cout << "String \"" << s << "\" was found in the file " << endl;

    }

    However, what do you mean by "store it in a variable" ? If you know what string you're looking for, it is in a variable already.

    • Login to reply the answers
  • 4 years ago

    You could use the function fscanf, you can look it up at cplusplus reference. This one is for reading string until there's a space. This is gonna be in a loop, after you use the fscanf use the stricmp (contact, aux); aux is a temporal variable where you save the data read with fscanf if (stricmp (contact, aux) == 0) ... the will be the condition when you find the name, you just have to read the telephone from the text...

    • Login to reply the answers
  • 10 years ago

    You're going to need to use the fstream header file and create an istream variable so you can open the file and read the contents in it. For example,

    #include <iostream>

    #include <fstream>

    #include <string>

    using namespace std;

    int main()

    {

    ifstream readFile.open("<insert the name of your file here>"); //

    string word; // will hold a single word from the file

    bool found = false; //determines if a word was found

    // To search for a particular word, in example, "Bob"

    while( readFile >> word )

    {

    if( word == "Bob"){

    cout <<"The word has been found." << endl;

    found = true;

    }

    }

    if( bool = false)

    cout <<"The word wasn't found." << endl;

    return 0;

    }

    Hope this helps you out

    • Login to reply the answers
Still have questions? Get your answers by asking now.