9 Replies - 58467 Views - Last Post: 20 December 2013 - 07:19 AM Rate Topic: -----

#1 Michael_Scott  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 13
  • Joined: 19-November 13

How to search for words in text file?

Posted 11 December 2013 - 01:54 AM

I am having a lot of trouble with this search program. My professor gave us an assigment to read text file and search for certain words in it. I tried getting it to read the words from the file, but it just outputs gibberish. I tried using the strcmp and strstr operators, but every time it just reads the first few words from the file. Here's a copy of his assignment:

“Write a C++ program to search a text file for occurrences of any of the following trigger words: "KALE", "ARTISANAL", "FIXIE", "KEROUAC", "JARMUSCH", "NERDCORE", "PBR", "TATTOO", "SCARF", "INDIE", "TURNTABLE". An "occurrence" means that the word in the file exactly matches the trigger, or the trigger appears as a substring of the word in the file. Your program will convert each word to uppercase before scanning it for an occurrence.

Your program will prompt the user for a filename, then will open that file and search for occurrences of the trigger words. Each time the program finds an occurrence, the program will print a line of text with the filename, the trigger word found, and the line number where it was found. There can be zero or more occurrences in the file; all will be reported. If no occurrence is found, the program will print "No Occurrences found". Use the file here and others. Your code should work for ANY filename supplied by the user. ”

I tried rearranging these string library functions, but still nothing. Either an error or just reading the first few lines. Or seeing nothing at all. After the user types in the filename, I call the function wordSearch with the name of the file as the argument. I have a two-dimensional array with one size, SIZE, which is 11, the number of words, and another size, MAX, which 13, which is the maximum number that I want the program to read up to so that the program does not go past the array's boundaries. (I probably don't need this though). In lines 46-73, I am trying to have the program step through the array of words while reading the file. The idea is that I want the program to read each word in the file until it reaches the end of the file, and if a word in the file matches a word in the array then I want it to display the word, where it’s been found, and how many times it was found. Right now I just want to start off with reading the text file and comparing words. Here's my code below:

#include <iostream>
#include <cstring>
#include <fstream>
#include <string>

using namespace std;
bool wordSearch(ifstream &);

int main()
{
	string fileName;	
	bool wordFound;
	ifstream file;
	cout << "Enter a file name\n";
	getline(cin, fileName);
	int count = 0;

	file.open(fileName);
	if (!file)
	{
		cout << "Dang. The file was not found." << endl;
		return 1;
	}
wordFound = wordSearch(file);
if (wordFound)
	cout << "The words have been found" << endl;
else
{
	cout << "Not found" << endl;
}
return 0;
}	
	
bool wordSearch(ifstream &hipsters)
{
	int index;
	int position = -1;
	const int SIZE = 11;
	const int MAX = 13;
	string fileWords;
	char words[SIZE][MAX] = {"kale", "artisanal", "fixie", "kerouac", "jarmusch", "nerdcore", "pbr", "tattoo", "scarf", "indie", "turntable"};
	char *strPtr = NULL;
	bool found = false;
	

	while(!hipsters.eof())
	{
		for (index = 0; index < SIZE; index++) //Loop that steps through each word	
		words[index];
		{
			for (index = 0; index < SIZE; index++) //loop that checks to see if each word can be found in the file
			strstr(hipsters, words); //strstr function searches for strings even if they are hidden in other strings
			found = true;
			}		
			return 0;
		
	}
	return found;
}

// for all words infile
// for all trigger words
// if trigger or substring
// print message


The errors I've been getting are as follows:

1>c:\users\mine\desktop\fall qtr 2013 notes and hw\cs 2360\file search\file search\file search.cpp(52): error C2665: 'strstr' : none of the 2 overloads could convert all the argument types
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\string.h(196): could be 'const char *strstr(const char *,const char *)'
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\string.h(220): or 'char *strstr(char *,const char *)'
1> while trying to match the argument list '(std::ifstream, char [11][13])'

I would appreciate any help with this to get me started.

Is This A Good Question/Topic? 0
  • +

Replies To: How to search for words in text file?

#2 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: How to search for words in text file?

Posted 11 December 2013 - 02:16 AM

To compare strings, use strcmp(), instead of strstr(). strstr() will give you false positives: indies is not the same word as indie, but strstr() will tell you that indie was found.

Before that though, make a sentence, and be sure you can separate each word out of the sentence. Words can be recognized because they have an alphanumeric char to start with, and either a space, or a punctuation mark of some kind (newline, comma, period, semi-colon, etc.), at the end of them.

I would let everything else wait until you can identify each word in several sentences with varying sentence structure.
Was This Post Helpful? 0
  • +
  • -

#3 Michael_Scott  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 13
  • Joined: 19-November 13

Re: How to search for words in text file?

Posted 11 December 2013 - 02:19 AM

I'm not sure about strcmp... strcmp compares the length of the strings, not their content, so if I get a string of the same length won't it just say it's true even if it's not the same word?
Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6245
  • View blog
  • Posts: 24,013
  • Joined: 23-August 08

Re: How to search for words in text file?

Posted 11 December 2013 - 04:16 AM

Quote

strcmp compares the length of the strings, not their content


Really? Have you read the manual?
Was This Post Helpful? 1
  • +
  • -

#5 baavgai  Icon User is online

  • Dreaming Coder
  • member icon


Reputation: 6979
  • View blog
  • Posts: 14,598
  • Joined: 16-October 07

Re: How to search for words in text file?

Posted 11 December 2013 - 04:51 AM

First, why are you using C strings in C++? Unless it's a requirement, loose the #include <cstring> and the strcmp.

Now, learn to indent consistently. In fact, from now on, ALWAYS use curly braces, even if they are optional.

e.g.
bool wordSearch(ifstream &hipsters) {
	int index; // why is this here?
	int position = -1;
	const int SIZE = 11;
	const int MAX = 13;
	string fileWords;
	char words[SIZE][MAX] = {"kale", "artisanal", "fixie", "kerouac", "jarmusch", "nerdcore", "pbr", "tattoo", "scarf", "indie", "turntable"};
	char *strPtr = NULL;
	bool found = false;


	while (!hipsters.eof()) {
		// you NEVER read anything from this file!?!
		for (index = 0; index < SIZE; index++)
			words[index]; // this does what, exactly?

		{ // we no longer have a loop, but a nice block

			for (index = 0; index < SIZE; index++) 
				strstr(hipsters, words); // you are calling a function and doing nothing with the return value
			found = true; // why?
		}
		return 0; // you, um, leave?

	}
	return found;
}



Use more functions. Be clear on what each is doing. e.g.
// takes a stream and a list of words, returns words found
int wordSearch(istream &, const std::string words[]);

// if the word is contained in the list of words, return true
bool isMatch(const std::string words[], const std::string &word);

// so

int wordSearch(istream &hipsters, const std::string words[]) {
	int found = 0;
	while (!hipsters.eof()) {
		std:string word;
		// read a word from hipsters ( your name, not mine )
		// your code here
		if (isMatch(words, word)) {
			// weren't you supposed to do something?
			// "if trigger or substring"
			// "print message"
			found++;
		}
	}
	return found;
}




You must think about the problem. Throwing code at the wall and hoping something will stick is not going to work. Break it down into smaller problems. Can you loop through the file, read each word, and just print it?

Hope this helps.
Was This Post Helpful? 1
  • +
  • -

#6 Michael_Scott  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 13
  • Joined: 19-November 13

Re: How to search for words in text file?

Posted 16 December 2013 - 12:46 AM

View PostJackOfAllTrades, on 11 December 2013 - 04:16 AM, said:

Quote

strcmp compares the length of the strings, not their content


Really? Have you read the manual?


Whoops, read the post, got it now.
Was This Post Helpful? 0
  • +
  • -

#7 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 387
  • View blog
  • Posts: 1,663
  • Joined: 16-May 09

Re: How to search for words in text file?

Posted 16 December 2013 - 05:23 AM

Also, there is something about the way you are performing I/O operations. The way you should do this in C++ by the use of streams is different than the methods you use in C.
There is a golden tutorial on this matter here, written by Bench which is located here.
Basically what you need to do is to implement a reading loop in this fashion:
ifstream file("test.txt");
string word;
while(file>>word) { //you could also use getline here
    //do something
}

Spoiler

Was This Post Helpful? 0
  • +
  • -

#8 Ambitious  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 133
  • Joined: 08-May 13

Re: How to search for words in text file?

Posted 16 December 2013 - 04:51 PM

Its pretty simple, here I coded it for you:
Contents of test.txt:
This is a test.
This is a test for the word KALE
This is a test for NERDCORE
Lol just one more test,KEROUAC!
Alright goodbye.#TURNTABLE
lel



C++ Source code:
#include <iostream>
#include <string>
#include <fstream>
void searchFile(std::string file);

int main()
{
    std::string userInput;
    std::cout<<"File: ";
    std::getline(std::cin,userInput);
    searchFile(userInput);
    std::cin.get();
}

void searchFile(std::string file)
{
    std::ifstream buffer;
    buffer.open(file.c_str());
    for(std::string temp;!buffer.eof();std::getline(buffer,temp))
    {
        if(temp.find("KALE")!=std::string::npos)
            std::cout<<temp<<std::endl;
        else if(temp.find("ARTISANAL")!=std::string::npos)
            std::cout<<temp<<std::endl;
        else if(temp.find("FIXIE")!=std::string::npos)
            std::cout<<temp<<std::endl;
        else if(temp.find("KEROUAC")!=std::string::npos)
            std::cout<<temp<<std::endl;
        else if(temp.find("JARMUSCH")!=std::string::npos)
            std::cout<<temp<<std::endl;
        else if(temp.find("NERDCORE")!=std::string::npos)
            std::cout<<temp<<std::endl;
        else if(temp.find("PBR")!=std::string::npos)
            std::cout<<temp<<std::endl;
        else if(temp.find("TATTOO")!=std::string::npos)
            std::cout<<temp<<std::endl;
        else if(temp.find("SCARF")!=std::string::npos)
            std::cout<<temp<<std::endl;
        else if(temp.find("INDIE")!=std::string::npos)
            std::cout<<temp<<std::endl;
        else if(temp.find("TURNTABLE")!=std::string::npos)
            std::cout<<temp<<std::endl;
    }
}



Output:

This is a test for the word KALE
This is a test for NERDCORE
Lol just one more test,KEROUAC!
Alright goodbye.#TURNTABLE

This post has been edited by Ambitious: 16 December 2013 - 04:52 PM

Was This Post Helpful? 0
  • +
  • -

#9 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 5884
  • View blog
  • Posts: 20,085
  • Joined: 05-May 12

Re: How to search for words in text file?

Posted 19 December 2013 - 10:55 PM

When you start duplicating code like that, it is a code smell that indicates that you are doing something wrong.

The code can be slightly improved by using a helper function, but can be greatly improved by making it data driven.
Was This Post Helpful? 0
  • +
  • -

#10 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: How to search for words in text file?

Posted 20 December 2013 - 07:19 AM

What you should do is put all the target words into a 2D array or other string container suitable for looping through.

Then use strstr() (or it's C++ equivalent), to search array[i] for each target word:
//in pseudo code:
for(every word you need to search through) {

   for(i=0;i<NumberOfTargetWords;i++)  {
      ptrToChar=strstr(word,targetWords[i])
      if(ptrTochar) 
         print found: word, targetWords[i]
         //etc.
   }
}



strcmp() is not what you want if you need to search for sub-strings, as well.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1