Hi am trying to make a simple application that write and read from and to a text file the problem is that i want to be able to aerch in the text file for an specific line.

the text file is a list of words with a meaning each word, the application ask for what word to search and i want to cout<< the specific line containing that word..

could someone can help me ??

Recommended Answers

All 35 Replies

yes -- read each line sequentiall from star to finish until you get the line you want. use fstream's getline() to read an entire line then check only the first word to see if the line is the one you want.

Don't attempt to code all of that at one time. First get your program to open the file for reading. After that is code and compiles without error, add a loop using getline() to read each line. Get that working then code the next part.

ok this is what i got

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	string line;
	char word;
	
	fstream dict("c://example.txt",ios::in);

	if (!dict.is_open()){ 
		cout << "Unable to open file";
		exit(1);
	}
	cout<<"Enter word to search \n";
	cin>>word;
	while(getline(dict,line)) 
		cout<<line<<"\n";
		

	return 0;
}

this is the part i know, now what ?


thanks in advanced !!

expand the while loop to extract the first word (hint: use string's find() method to locate the first space), then compare that with the string that you entered from the command line. If they are the same then you can stop that loop.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	string line;
	char* word="";
	size_t i;
	fstream dict("c://example.txt",ios::in);

	if (!dict.is_open()){ 
		cout << "Unable to open file \n";
		exit(1);
	}
	cout<<"Enter word to search \n";
	cin>>word;

	while(getline(dict,line))
        i = line.find(word);
       
        if (line.compare(word) != 0){
               cout << "result " <<line << endl;

      }else

		cout<<"Not in list"<<"\n";
		

	return 0;
}

I have the idea of what you are saying but dont know how to put it in code

A little off. First you need to put braces around that entire while statement. Next, the find mentiond returns string::npos if the word is not found. You need to add a check to see if the find method worked or not.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	string line;
	char* word="";
	size_t i;
	fstream dict("c://example.txt",ios::in);

	if (!dict.is_open()){ 
		cout << "Unable to open file \n";
		exit(1);
	}
	cout<<"Enter word to search \n";
	cin>>word;
	{
	while(getline(dict,line))   //read line by line
	i = line.find(word);    //try to find the var word in the string line an assign it to i
	
	if (i!=string::npos)      // dont exactly know what it does
  cout<<i<<" not found";      
	else 
		line.compare(word) != 0;  //compare the string line to the var word 
    cout << "result " <<line << endl;
	exit (1);
  
}

	return 0;
}

I know youre trying to make me understand but am a little lost here really !!
i put comments around the lines to see if i understand what each does correctly , please correct me if am wrong..

thanks a lot

Member Avatar for iamthwee

Why not try a trivial example first without reading a text file. When you are confident with how it works try it with a text file.
Questions (hints)
Are you getting your logic muddled up? Do you even need the line.compare(word)?
http://www.cplusplus.com/reference/string/string/find.html

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	string line;
	char* word="";
	size_t i;
	fstream dict("c://example.txt",ios::in);

	if (!dict.is_open()){ 
		cout << "Unable to open file \n";
		exit(1);
	}
	cout<<"Enter word to search \n";
	cin>>word;
	{
	while(getline(dict,line))   //read line by line
	i = line.find(word);    //try to find the var word in the string line an assign it to i
	
	if (i!=string::npos)      // dont exactly know what it does
  cout<<i<<" not found";      
	else 
		line.compare(word) != 0;  //compare the string line to the var word 
    cout << "result " <<line << endl;
	exit (1);
  
}

	return 0;
}

I know youre trying to make me understand but am a little lost here really !!
i put comments around the lines to see if i understand what each does correctly , please correct me if am wrong..

thanks a lot

you put the braces in the wrong place. This is how it should look:

while(getline(dict,line))   //read line by line
{ // start of while

    // your code goes here

} // end of while

I put it there but still dont work !!

it is my code right or wrong?

re-post your most recent code. What you posted earlier was not right, as I mentioned before. Pay close attention to the placement of the braces. compilers do not accept sloppy coding.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
using namespace std;

int main()
{
	
	string line;
	char word[65];
	size_t found=' ';

	fstream dict("c://dict.txt",ios::in);

	if (!dict.is_open()){ 
		cout << "Unable to open file \n";
		exit(1);
	}
	cout<<"Welcome \n"
		<<"Cois 270 \n"
		<<"\n"
		<<"\n"<<endl;

	cout<<"Enter a word to search: ";
	cin>>word;

	while(getline(dict,line)){
		if ( (found = line.find (word, 0)) != string::npos )

			cout<<"\n"<<line<<endl;				
	}
			
	if ( (found != line.find (word, 0)) == string::npos )
	cout<<"'"<<word<<"'"<<" is not found \n";

dict.close();
return 0;

}

somehow or someway i get it to work, dont know if is the right way to do it but it work...

I limit how much is display in the result by

char word[65]="";

if i let the char word; alone it display the entire text file starting from the word i was searching.

now am trying to convert the char word to lowercase in case someone type a word in upper
I try to use cast and tolower() but cast dont work and tolower() can convert int to char[65]...


Thanks a lot " Ancient Dragon " this is the best way to learn !!

that while loop is close to being ok, but not quite. If the word is found you need to jump out of that loop if you don't then the if statement that is after the loop will not work correctly.

That loop is also still incorrect because the return value of find could be somewhere in the middle of the string, which is not what you want. For example, lets say the word you want to find is "Mary" and the sentense is "Hello my name is Mary.". In this example the find method will return a value of 17 because "Mary" starts in position 17 of the string. But you want a string with the word "Mary" at the beginning of the string and ignore other places. This means that if statement has to be changed to check if found is 0, not npos.

while(getline(dict,line)){
    if ( (found = line.find (word, 0)) == 0 )
    {                                      
          cout<<"\n"<<line<<endl;	
          break;
     }
}

to convert to lower-case you need to call tolower() in a loop and call it for every letter in the word. There is another way, assuming word is std::string object and not a character array.

translate(word.begin(), word.end(), word.begin(), tolower);

You will also have to do the same thing with each line read from the file, just to insure that they are all the same case.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
using namespace std;

int main()
{
	
	string line;
	char word[65]="";
	char ans=' ';
	size_t found=' ';

	fstream dict("c://dict.txt",ios::in);

	if (!dict.is_open()){ 
		cout << "Unable to open file \n";
		exit(1);
	}
	cout<<"Welcomey\n"
		<<"Cois 270\n"
		<<"\n"
		<<"\n"<<endl;
	while(toupper(ans)!='X'){
	cout<<"Enter a word to search: ";
	cin>>word;

	while(getline(dict,line)){
		if ( (found = line.find (word, 0)) != string::npos )

			cout<<"\n"<<line<<endl;				
	}
			
	if ( (found != line.find (word, 0)) == string::npos ){
	cout<<"'"<<word<<"'"<<" is not found \n";
	}
		cout<<"Press 'X' to exit or any other key to continue searching ";
		cin>>ans;
}
dict.close();
return 0;

}

for now i add a loop to see if you want to search more words or not, but now the if statement that check if the word is not found is not validating and maybe is the braces :(

thanks

you obviously ignored my previous post so I'll ignore yours.

i change to ==0 but when i type a word that i know is in the text file at the beginning of the line it validate for !=0
BTW i check different words all validate by !=0 and always display the same line from the text file

you obviously ignored my previous post so I'll ignore yours.

what ???

anyway the line that display is the first line in the text file...

well, when you get around to posting something that includes the fix that I last mentioned I might get around to answering you. In any event -- to late for me tonight, going to sleep. Good night. :)

AD

I already did what you said

i change to ==0 but when i type a word that i know is in the text file at the beginning of the line it validate for !=0
BTW i check different words all validate by !=0 and always display the same line from the text file(the line is the first one from the text file)

i post the other code because i didn't receive an answer so i move on to other thing when i was typing that you were typing your post ...

so.. no more help ??

please i need to finish this

I can't read your mind -- post most recent code that includes the changes we have already discussed. I'm not going to repeat myself, so re-read all previous posts to this thread if you need to. If what we have suggested doesn't work then post the code you tried. Don't guess -- do copy/paste.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
using namespace std;

int main()
{
	
	string line;
	char word[20]="";
	char ans=' ';
	size_t found=' ';


	cout<<"Welcome"<<endl;

	fstream dict("c://dict.txt",ios::in);

	if (!dict.is_open()){ 
		cout << "Unable to open file \n";
		exit(1);
	}
	
	while(toupper(ans)!='X'){
		
	cout<<"Enter a word to search: ";
	cin>>word;

	while (getline(dict,line)) {
		if ((found = line.find(word,0)) != string::npos )

			cout<<"\n"<<line<<endl;
	
	} 
	
	if ((found != line.find(word,0)) != string::npos )
		cout<<"not found \n";

	cout<<"Press 'X' to exit or any other key to continue searching ";
		cin>>ans;
	}

	dict.close();
return 0;

}

i try to change string::npos to ==0 and dont work

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
using namespace std;

int main()
{
	
	string line;
	char word[20]="";
	char ans=' ';
	size_t found=' ';


	cout<<"Welcome"<<endl;

	fstream dict("c://dict.txt",ios::in);

	if (!dict.is_open()){ 
		cout << "Unable to open file \n";
		exit(1);
	}
	
	while(toupper(ans)!='X'){
		
	cout<<"Enter a word to search: ";
	cin>>word;

	while(getline(dict,line)){
			if ( (found = line.find (word, 0)) == 0 ){
                                       
          cout<<"\n"<<"not found"<<endl;	
          break;
		} 
	}
	
		
		cout<<"\n"<<line<<endl;
		
	cout<<"Press 'X' to exit or any other key to continue searching ";
		cin>>ans;
	}

	dict.close();
return 0;

}

ok i try again now at least i get only the line with the exact word am looking to but i cant search again and anyway it validate the line ==0 ,
that means that i get the "not found" and the line with the exact word i was looking.

it read the text file once i can search all the words and it display the line in alphabetical order if i search "bear" its ok then i search "airplane" it get to the end of the file and i can search further..

you have to rewind the file back to the beginning. Before doing the while loop search call dict.seekg(0); And move that line that says "word not found" outside that loop because if the program goes there it means that the word was found.

commented: Nope, you don't have to use dict.seekg(0) to read the file again. -2
// reader.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
using namespace std;

int main()
{
	
	string line;
	char word[20]="";
	char ans=' ';
	size_t found=' ';


	cout<<"Welcome"<<endl;

	fstream dict("c://dict.txt",ios::in);

	if (!dict.is_open()){ 
		cout << "Unable to open file \n";
		exit(1);
	}
	
	while(toupper(ans)!='X'){
		
	cout<<"Enter a word to search: ";
	cin>>word;
	dict.seekg(0);
	while(getline(dict,line)){
			if ( (found = line.find (word, 0)) == 0 ){
                                       
          cout<<"\n"<<line<<endl;	
          break;
			}
	}
	
		if ( (found = line.find (word, 0)) != 0 ){
		cout<<"\n"<<word<<" not found"<<endl;
		
		}
	
	cout<<"Press 'X' to exit or any other key to continue searching ";
		cin>>ans;
	}

	dict.close();
return 0;

}

ok it work perfect like this it find the exact word not in between everything ok but until i type a word that is not found it display "not found" but i can search anything because it said "not found"

>but until i type a word that is not found it display "not found"
>but i can search anything because it said "not found"
Your loop terminates in one of two ways: A word is found and you use break to jump out early, or a word is not found and you loop all the way to end-of-file. After the loop, you seek back to the beginning of the file, but because seekg doesn't reset the eofbit, you have to call clear if you want the loop to run again. On streams with an error state set, any input request is ignored. Replace this:

dict.seekg(0);

With this:

dict.clear();
dict.seekg(0);

thanks a lot everything work fine now, i wold like to add the convert to lower case(because if someone type the word in uppercase it wont find anything) but i do not know if that is a lot of code to add

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.