Friday, July 31, 2009

C++ taking input and comparing it against a string?

I'm working on coding a c++ program but i'm having a few problems. Bassically i'm trying to copy the contents of a input text file in to a string, and then allow the user to input a word or string of the user's own to cross reference with the input string from the file and show the index where it first occured.





Thus far i've been able to get the contents of the input file in to the string, but i can't figure out what i'm doing wrong as far as taking the user's string and comparing it.





// user_word is holding the input string from user





int i = hold_all_text.find(user_word);





if(i != string::npos) {


cout %26lt;%26lt; "Found match for your word " %26lt;%26lt; user_word %26lt;%26lt; " at " %26lt;%26lt; i %26lt;%26lt; endl;


}


else


cout %26lt;%26lt; "No match in file contents.\n";


return 0;





Going in to the debugger it just shows the value of "i" as being -1





If anyone could help i would greatly appreciate it, i've been trolling around forums but i cannot seem to find anyone who is having exactly the same issue

C++ taking input and comparing it against a string?
The only thing I can think of is your strings hold_all_text and user_word do not contain what you think they do. The result you're getting is telling you hold_all_text does not contain user_word, and that's probably true. See the simple example below that I wrote to illustrate, it does what you're trying to do, and it works.





Some suggestions:


It might be better to read the contents of the file into a vector%26lt;string%26gt;, then you can report line number and position in the line for strings to be found.


Even if you don't use a vector, you should do your search in a loop, to find all occurrences of user_word. The version of find you're using, that I use below, takes an optional pos argument, the index to start the search. You can use this to continue searching in a string after you've found the first occurrence of the substring.





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





int main(int argc, char *argv[]) {


string s0("the quick brown fox jumped over the lazy dog");


string s1;


size_t loc;





cout %26lt;%26lt; "s = " %26lt;%26lt; s0 %26lt;%26lt; endl;


cout %26lt;%26lt; "Enter substring to find: ";


getline(cin, s1);


cout %26lt;%26lt; "\"" %26lt;%26lt; s1 %26lt;%26lt; "\"";


if ((loc = s0.find(s1)) != string::npos) {


cout %26lt;%26lt; " found at index " %26lt;%26lt; loc %26lt;%26lt; endl;


} else {


cout %26lt;%26lt; " not found." %26lt;%26lt; endl;


}


return 0;


}


No comments:

Post a Comment