943,723 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Marked Solved
  • Views: 920
  • C++ RSS
May 11th, 2008
0

Compare a string with a file.

Expand Post »
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
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
tharris7 is offline Offline
1 posts
since May 2008
May 11th, 2008
0

Re: Compare a string with a file.

Click to Expand / Collapse  Quote originally posted by tharris7 ...
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:
cpp Syntax (Toggle Plain Text)
  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 Nick Evan; May 11th, 2008 at 7:20 am.
Moderator
Featured Poster
Reputation Points: 4142
Solved Threads: 394
Industrious Poster
Nick Evan is offline Offline
4,132 posts
since Oct 2006

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: need serious help!!!!!!
Next Thread in C++ Forum Timeline: Simple aplication typing?





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC