searching a text file for a string

Hi,

I want to find a certain line in a text file. The text file looks like this:

hi=hi!
bye=bye!
how are you doing=good!


I am using getline().

Here is my code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 while(true){
 cin >> human;

bool search = true;
while(search == true){

getline (indata, line, '=');

if(line == human){
 search = false;

getline (indata,line,'\n');
				   
     cout << line << endl;
    }
  }
}


PS:MV C++ 2010 Express

Thank you!
Last edited on
Hello? Can anybody help me?
Try
 
getline(cin,human);

and
1
2
if(line.compare(human)==0)
search=false;

You are using strings so the "==" operator is not valid (http://www.cplusplus.com/reference/string/string/compare/).
Okay, I tried that but it still does not work right.

I need a function that searches a line for a phrase and if it does not find the phrase it searches one line down. When it does find it it would output what ever is on the other side of the equal sign('=').
What kind of output do you receive? Btw this is much easier to do using char arrays if your new to c++ (in my opinion).
Last edited on
Regarding operator==, if line is a string, then line == "test" and "test" == line should both be valid. I think the cplusplus.com info on string is missing some information.

http://www.sgi.com/tech/stl/basic_string.html
Last edited on
The original code looks like it should work as long as you don't expect human to have any spaces in it, although the sample input suggests that isn't something one should expect. Deplorable indentation, btw.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
while(true)
{
    // check to see if there's a '\n' in the buffer from previous input
    if ( cin.peek() == '\n' )
        cin.ignore() ;

    getline(cin, human) ;

    bool search = true;
    while(search == true){

        getline (indata, line, '=');

        if(line == human){
            search = false;

            getline (indata,line,'\n');
				   
            cout << line << endl;
        }
    }
}


I would suggest changing this around so input failure with getline on indata is accounted for.
@cire

This solution only works if I input it in the same order that the text file is in. How would I make it so it works in different orders of input?

Thanks for all the help!

Edit: After playing around with it, I have found that getline() only reads the file in order. What do I do now?
Last edited on
Start over at the beginning of the file every time you have a new search.
Topic archived. No new replies allowed.