Thread: Searching for a string in a file

  1. #1
    Registered User
    Join Date
    Jan 2003

    Searching for a string in a file


    I have just started looking at C++ and need help with the following program.

    I am trying to write a program where a user enters there name and other details. The program then checks a text file to see if the user already exists, if so removes the 'old' details from the file and re-inserts the new data.

    However, I am having problems finding out how to search for a specific string within a file. I am currently using 'Teach Yourself C++ in 21 Days', but it does not seem to go into that much depth for string searches.

    Can anyone please advise how I might search for a string in a file, baring in mind that I am a begineer to this head-ache language.


  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    How do you store the data (strings) in the file?

    If it's something like this:
    100 25 8 12
    120 23 11 19
    115 19 6 13
    You could read a whole line ( getline() ) and then use strcmp() to compare that string with whatever you want to compare it to. If it doesn't match, search on, otherwise you read the data on the next line.

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    CIS and business major
    Join Date
    Aug 2002
    #include <vector>
    #include <string>
    #include <iostream>
    #include <fstream>
    using namespace std;
    int main()
    	string findThis;
        string one;
    	string item;
    	vector<string> v;
    	cout << "Please enter a string to search for: ";
    	cin >> findThis;
    	ifstream in("file.txt"); 
    		getline(in, item);
    		one = one + item + "\n";
            if(one.find(findThis) < 0)
                cout << "didn't find the word you're looking for" << endl;

    should do the trick

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 03:13 PM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
Website Security Test