string.compare for c++
I am asking user to input a word then have my program compare it with an input .txt file but even tho I type in exactly a word in data.txt it still executes false.
//------------in my data.txt---------
// Banana Bed Today
// Apples Chair Window
// Corn Tomorrow Hive
string testData;
cout<<"enter Data: ";
cin>>testData;
for(i=0; i<s.size()-1; i++){
if (t开发者_运维问答estData.compare(s[i]->name) == 0)
cout<<"Right\n";
if (youkno.compare(s[i]->name) != 0)
cout<<"Wrong\n";
}
if i prompt Banana then output excuted wrong
If you replace:
for(i=0; i<s.size()-1; i++){
with:
for(i=0; i<s.size(); i++){ // Adjusting to check last entry as well.
cout << "[" << s[i]->name << "][" << testData << "]" << endl;
you may find it becomes blindingly obvious. There's a good chance that one of your strings is not quite what you expect.
What is in s[i]->name
? If you read that data from a file, you may have included the line endings in the name
variable.
Also, why not use operator==
?
EDIT: just noticed you have an off by one error. your for loop should be
for(i=0; i<s.size(); i++)
Otherwise you don't compare the last value item in s
精彩评论