RSS Forums RSS

Compare a string with a file.

Please support our C++ advertiser: Programming Forums
Thread Solved
Reply
Posts: 1
Reputation: tharris7 is an unknown quantity at this point 
Solved Threads: 0
tharris7 tharris7 is offline Offline
Newbie Poster

Compare a string with a file.

  #1  
May 11th, 2008
Hi,

I'm quite new to C++ so all help is appreciated.

I have a program that makes a string of at least three characters. I want to be able to compare the string to a list of words (i.e. dictionary) in a separate file, and then output the string if it is in the dictionary.

The string 'word' is a string object so I'm having problems with strcmp (which only takes chars?). The reason I used a string object is because I have to use substr and concatenation, and I'm not very familiar with using char arrays. (I've mostly done Java before).

What I have got so far:

char dictword[32];    
ifstream dictionary("dictionary.txt");

while (dictionary>>dictword)
{      
        if (strcmp(dictword,word)!=0)
   		cout<<word<<'\n";
}

Thanks in advance,
Tim
AddThis Social Bookmark Button
Reply With Quote  
Posts: 2,353
Reputation: niek_e has much to be proud of niek_e has much to be proud of niek_e has much to be proud of niek_e has much to be proud of niek_e has much to be proud of niek_e has much to be proud of niek_e has much to be proud of niek_e has much to be proud of niek_e has much to be proud of niek_e has much to be proud of 
Solved Threads: 256
Featured Poster
niek_e's Avatar
niek_e niek_e is offline Offline
Nearly a Posting Maven

Re: Compare a string with a file.

  #2  
May 11th, 2008
Originally Posted by tharris7 View Post
char dictword[32];    
}


Why use char arrays when c++ provides you with strings? Mixing up C and C++ is very confusing and will require a lot of casting. So what about something like:
  1. string word = "abc";
  2. string dictword;
  3. ifstream dictionary("dictionary.txt");
  4. while (getline(dictionary, dictword, ' '))
  5. {
  6. if (word == dictword)
  7. cout << "found: " << word << "\n";
  8. }
Off course you'll have to build in some error checking etc. And this code assumes that all words in textfile are delimited with a space. So some more work is required from you
Last edited by niek_e : May 11th, 2008 at 6:20 am.
Want better/more replies to your questions? Wrap your code in [code] [/code] tags!
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.



Views: 576 | Replies: 1 | Currently Viewing: 1 (0 members and 1 guests)

 

Thread Tools Display Modes
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 12:32 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC