C++ School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C++ Expert!

Join 300,338 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,675 people online right now. Registration is fast and FREE... Join Now!




string search in a file

 

string search in a file

arobbins

9 Jun, 2009 - 09:02 PM
Post #1

New D.I.C Head
*

Joined: 26 May, 2009
Posts: 6

Here is the problem(this is for a intro to C/C++ class):

Write a program that asks the user for a file name and a string to search for. The program should search the file for every occurrence of a specified string. When the string is found, the line that contains it should be diplayed. After all the occurrences have been located, the program should report the number of times the string appeared in the file.

I created a text file with the following text:

one two three four five
two three four five six
three four five six seven
four five six seven eight
five six seven eight nine
six seven eight nine ten

The problem I'm having right now is trying to search for the string within the file. I know you can use strstr to search for a string within a string, but I'm not sure how to search within the file. What I have so far is below. Any help to point me in the right direction would be great.

CODE
// Chapter 12, Program Challenge 6 - string search
// This program will search for a specific string (based on user input)
// in a file and then return all lines that include that string.  
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main()
{
    const int SIZE = 31;                 // constant for size of character string
    char stringSearch[SIZE];             // used to search for the string in the file
    char fileName[SIZE];                 // to hold the file name
    ifstream inputFile;                  // input file
    int counter = 0;                     // counter for counting number of string occurences
    char *stringPtr;                     // points to the string
    
    // Prompt user to select a string to search from the file
    cout << "Enter a word or string of words to search for: ";
    cin.getline(stringSearch, SIZE);
    // Get the input file name
    cout << "Enter the name of a file that you would\n";
    cout << "like to search for a string within: ";
    cin >> fileName;
    
    
    // Open the file for input.
    inputFile.open(fileName);
    if(!inputFile)
    {
         cout << "Cannot open " << fileName << endl;
         system("pause");
         return 0;
    }
    
    // Search file for user-input string
    while(!inputFile.eof())
    {
         inputFile.getline(stringSearch, SIZE);
         cout << stringSearch;
         cout << endl;
    }                  
    
    cout << endl;
    
    // Close the files.
    inputFile.close();
    
    system("pause");
    return 0;
}


User is offlineProfile CardPM
+Quote Post


apw5020

RE: String Search In A File

9 Jun, 2009 - 11:03 PM
Post #2

D.I.C Addict
****

Joined: 26 Mar, 2009
Posts: 576



Thanked: 58 times
My Contributions
You should try researching/using C++ strings. They are much easier to work with.
User is offlineProfile CardPM
+Quote Post

arobbins

RE: String Search In A File

10 Jun, 2009 - 04:44 AM
Post #3

New D.I.C Head
*

Joined: 26 May, 2009
Posts: 6

QUOTE(apw5020 @ 9 Jun, 2009 - 11:03 PM) *

You should try researching/using C++ strings. They are much easier to work with.


I have done many searches to try and figure out how to search a file for a string, and haven't come up with anything that I understand at my level. We're supposed to do this with what we have learned from the book so far...

QUOTE(arobbins @ 10 Jun, 2009 - 04:44 AM) *

QUOTE(apw5020 @ 9 Jun, 2009 - 11:03 PM) *

You should try researching/using C++ strings. They are much easier to work with.


I have done many searches to try and figure out how to search a file for a string, and haven't come up with anything that I understand at my level. We're supposed to do this with what we have learned from the book so far...


perhaps you could point me in the right direction?
User is offlineProfile CardPM
+Quote Post

arobbins

RE: String Search In A File

10 Jun, 2009 - 07:56 AM
Post #4

New D.I.C Head
*

Joined: 26 May, 2009
Posts: 6

QUOTE(arobbins @ 9 Jun, 2009 - 09:02 PM) *

Here is the problem(this is for a intro to C/C++ class):

Write a program that asks the user for a file name and a string to search for. The program should search the file for every occurrence of a specified string. When the string is found, the line that contains it should be diplayed. After all the occurrences have been located, the program should report the number of times the string appeared in the file.

I created a text file with the following text:

one two three four five
two three four five six
three four five six seven
four five six seven eight
five six seven eight nine
six seven eight nine ten

The problem I'm having right now is trying to search for the string within the file. I know you can use strstr to search for a string within a string, but I'm not sure how to search within the file. What I have so far is below. Any help to point me in the right direction would be great.

CODE
// Chapter 12, Program Challenge 6 - string search
// This program will search for a specific string (based on user input)
// in a file and then return all lines that include that string.  
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main()
{
    const int SIZE = 31;                 // constant for size of character string
    char stringSearch[SIZE];             // used to search for the string in the file
    char fileName[SIZE];                 // to hold the file name
    ifstream inputFile;                  // input file
    int counter = 0;                     // counter for counting number of string occurences
    char *stringPtr;                     // points to the string
    
    // Prompt user to select a string to search from the file
    cout << "Enter a word or string of words to search for: ";
    cin.getline(stringSearch, SIZE);
    // Get the input file name
    cout << "Enter the name of a file that you would\n";
    cout << "like to search for a string within: ";
    cin >> fileName;
    
    
    // Open the file for input.
    inputFile.open(fileName);
    if(!inputFile)
    {
         cout << "Cannot open " << fileName << endl;
         system("pause");
         return 0;
    }
    
    // Search file for user-input string
    while(!inputFile.eof())
    {
         inputFile.getline(stringSearch, SIZE);
         cout << stringSearch;
         cout << endl;
    }                  
    
    cout << endl;
    
    // Close the files.
    inputFile.close();
    
    system("pause");
    return 0;
}




can anyone help me with this? point me in the right direction?
User is offlineProfile CardPM
+Quote Post

Plus

RE: String Search In A File

10 Jun, 2009 - 09:08 AM
Post #5

D.I.C Regular
Group Icon

Joined: 24 Nov, 2008
Posts: 374



Thanked: 35 times
Dream Kudos: 75
My Contributions
search in a file .. there is only one way to do that

--------------------------
a. read part of the file into a buffer

b. search for the string in the buffer

c. if found or file-end return true! if not read again
--------------------------

it's a loop in C++ using ifstream,

C++

bool SearchFileForString(const char &File_Name[],const char &key[])
{
ifstream File(File_Name,ios::in);
char buffer[256];

if(!File) return false;

while(!File.eof())
{
File >> buffer;

if(String_Search(buffer,key)) // function String_Search required !
return true;
}
return false;
}


User is offlineProfile CardPM
+Quote Post

Elcric

RE: String Search In A File

10 Jun, 2009 - 11:07 AM
Post #6

D.I.C Regular
Group Icon

Joined: 2 May, 2009
Posts: 257



Thanked: 15 times
Dream Kudos: 1500
My Contributions
biggrin.gif
Hello,

I thought your project was interesting.

I playing around with it. Here is a very very rough draft.

Good Luck!
CODE


//************************************
// NOTE:  ASCII Table, '0' to '9' are represented as 48 to 57
//************************************
// This program will search for a specific string (based on user input)
// in a file and then return all lines that include that string.  
//************************************
#include <cstring>
#include <ctime>
#include <ctype.h>
#include <fstream>                            // file I/O
#include <iomanip>                            // format manipulation
#include <iostream>
#include <limits>
#include <map>
#include <math.h>
#include <sstream>
#include <stddef.h>
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>                            // converter functions
#include <string>
using std::istringstream;
using std::ifstream;
using std::string;
using std::cout;
using std::cin;
using std::cerr;
using std::map;
using std::multimap;

using namespace std;
//************************************
//In general, C++ strings are preferred over C strings.
//************************************
void CreateExampleTxtFile();
void PrintExampleTxtFile();
void SizeExampleTxtFile();
int SearchExampleTxtFile();
//************************************
int main(int argc, char* argv[])
{
    int choice = 0;
    bool exitt = false;

    do
    {
        system("CLS");

        cout << endl << endl << endl;
        cout << "           MENU" << endl;
        cout << "  ************************" << endl << endl;
        cout << "  1  Create new file." << endl;
        cout << "  2  Print new file" << endl;
        cout << "  3  Size new file" << endl;
        cout << "  4  Search new file." << endl << endl;
        cout << "     Enter 0 to exit" << endl << endl;

        //test validity of user input data


        //Get customer input

        cout << "  Please type a number from 0 to 4 and then press enter ==> ";

        cin >> choice;


        switch(choice)
        {
            //Call class member functions

        case 0:

            break;

        case 1:
            CreateExampleTxtFile();
            break;

        case 2:
            PrintExampleTxtFile();
            break;

        case 3:
            SizeExampleTxtFile();
            break;

        case 4:
            SearchExampleTxtFile();
            break;

        default:
            cout << endl << endl << endl;
            cout << "  Please select again." << endl << endl;
            break;
        }

        cout << endl << endl << endl;
        cout << "  Type the number 1 and press return to run this program again." << endl << endl << endl;
        cout << "  Type any key and press return to exit ==> ";

        cin >> choice;

        if (choice == 1)
            exitt = false;
        else
            exitt = true;
    }while(exitt == false);

    cout << endl << endl << endl;
    cout << "  ";
    system("PAUSE");

    return 0;
}
//************************************
//This function creates a file named example.txt
//and inserts six sentences into example.txt.
void CreateExampleTxtFile()
{
    ofstream myfile;
    myfile.open ("example.txt");
    if (myfile.is_open())
    {
        myfile << "one two three four five\n";
        myfile << "two three four five six\n";
        myfile << "three four five six seven\n";
        myfile << "four five six seven eight\n";
        myfile << "five six seven eight nine\n";
        myfile << "six seven eight nine ten\n";
        myfile.close();
    }
    else cout << "  Unable to open file";
}

//************************************
//This function reads a file named example.txt
//and prints contents to console.
void PrintExampleTxtFile()
{
    string line;

    ifstream myfile ("example.txt");
    system("CLS");
    if (myfile.is_open())
    {
        while (! myfile.eof() )
        {
            getline (myfile, line);
            cout << "  " << line << endl;
        }
        myfile.close();
    }

    else cout << "  Unable to open file";
}

//************************************
//This function prints the size of the example.txt file,
//on the console.
void SizeExampleTxtFile()
{
    long begin;
    long end;
    ifstream myfile ("example.txt");
    begin = myfile.tellg();
    myfile.seekg (0, ios::end);
    end = myfile.tellg();
    myfile.close();
    system("CLS");
    cout << endl << endl << endl;
    cout << "  File size is: " << (end - begin) << " bytes.\n";
}

//************************************
int SearchExampleTxtFile()
{
    const int SIZE = 200;                // constant for size of character string
    char fileName[SIZE];                 // to hold the file name
    ifstream inputFile;                  // input file
    int counter = 0;                     // counter for counting number of string occurences

    system("CLS");

    //************************************
    // Get user's file name
    cout << endl << endl << endl;
    cout << "  Enter the name of the file you want\n";
    cout << "  to search and press return ==> ";
    cin >> fileName;        //fileName is example.txt

    // Open user's file.
    inputFile.open(fileName);
    if(!fileName)
    {
        cout << endl << endl << endl;
        cout << "  Cannot open " << fileName << endl;
        cout << endl << endl << endl;
        cout << "  ";
        system("pause");
    }

    //************************************
    //reads a file named example.txt searches for user defined string
    //and prints results to console.
    multimap<string, int> words;
    map<int, string> lines;
    string str;
    ifstream input("example.txt");
    if(input.fail())
    {
        cerr<<"\n  The file could not be opened.";
        return -1;
    }
    int i=1;
    while(getline(input,str))
    {
        istringstream in(str);
        string s;
        while(in>>s)
        {
            words.insert(make_pair(s,i));
        }
        lines.insert(make_pair(i,str));
        i++;
    }
    string search;
    cout << "\n  Enter a word to search: ";
    cin >> search;

    cout << "\n  The number of matches = " << words.count(search) << '\n';
    multimap < string,int>::iterator it1=words.lower_bound(search);
    multimap < string,int>::iterator it2=words.upper_bound(search);
    while(it1 != it2)
    {
        int x=it1->second;
        map<int,string>::iterator iter = lines.find(x);
        cout << '\n' << x << " ) " << iter->second << '\n';
        it1++;
        while(true)
        {
            if(it1 != it2 && it1->second == x)
            {
                it1++;

            }
            else
            {
                break;
            }
        }
    }
    return 0;
}


I copy pasted your project into another one I was working on so you need to clean this up a lot, sorry.

The file search was fun!


User is offlineProfile CardPM
+Quote Post

apw5020

RE: String Search In A File

10 Jun, 2009 - 01:26 PM
Post #7

D.I.C Addict
****

Joined: 26 Mar, 2009
Posts: 576



Thanked: 58 times
My Contributions
Why would you write the program for him? He needs to do it on his own or else he will learn nothing from it...which is the number 1 rule on this website.

This post has been edited by apw5020: 10 Jun, 2009 - 01:27 PM
User is offlineProfile CardPM
+Quote Post

arobbins

RE: String Search In A File

10 Jun, 2009 - 02:36 PM
Post #8

New D.I.C Head
*

Joined: 26 May, 2009
Posts: 6

QUOTE(apw5020 @ 10 Jun, 2009 - 01:26 PM) *

Why would you write the program for him? He needs to do it on his own or else he will learn nothing from it...which is the number 1 rule on this website.


agreed... though i appreciate the help this is way too advanced for me to understand.... but i would still prefer to be directed to a good site that spells out how to do this type of search in a way i will be able to understand...
User is offlineProfile CardPM
+Quote Post

apw5020

RE: String Search In A File

10 Jun, 2009 - 02:58 PM
Post #9

D.I.C Addict
****

Joined: 26 Mar, 2009
Posts: 576



Thanked: 58 times
My Contributions
This tutorial looks like a good introduction to stings.
http://www.dreamincode.net/forums/showtopic42209.htm

Did you say you haven't learned them yet?


This post has been edited by apw5020: 10 Jun, 2009 - 03:03 PM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic

Time is now: 11/7/09 05:18PM

Live C++ Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month