Reputation: 49
I've created a program that takes in an input file with 1000+ entries formatted as such:
year, category, won, entity
I created a struct with a string element for each of parts of one entry. I now want to ask the user to input a specific entity's name such as "Emil Jannings" and return the index it is at so I can use that index to print out the line of information for that entity.
The first few lines of the input file are this:
year,category,winner,entity
1927,ACTOR,FALSE,Richard Barthelmess
1927,ACTOR,TRUE,Emil Jannings
1927,ACTRESS,FALSE,Louise Dresser
If the user inputted "Emil Jannings" as the input string, I want my loop to return the index it is at. My problem is that the loop returns 0 for i no matter what. Is there something fundamentally wrong with how my loop is set up? In addition theres a unknown amount of the same entity in the input file, Emil Jannings can show up more than once. How can I alter the loop to continue giving me every index it is found until the end of the input file? Thank you.
for(;(getline(in, str)); i++){
istringstream iss(str);
Oscars.push_back(Oscar_Awards());
getline(iss, str2, ',');
Oscars.at(i).year = str2;
getline(iss, str2, ',');
Oscars.at(i).category = str2;
getline(iss, str2, ',');
Oscars.at(i).won = str2;
getline(iss, str2, ',');
Oscars.at(i).entity = str2;
}
cout << "Input Name of Entity" << endl;
string input;
cin >> input;
bool found = false;
for(int i = 0; i < Oscars.size(); i++){
if(Oscars.at(i).entity.find(input)){
cout << "Found at " << i << endl;
found = true;
break;
}
}
Upvotes: 1
Views: 102
Reputation: 543
You are using string::find
instead of just comparing a string with a string.
Assuming entity
is of type string
. The following code should work fine.
bool found = false;
for(int i = 0; i < Oscars.size(); i++){
if(Oscars[i].entity == input){
cout << "Found at " << i << '\n';
found = true;
break;
}
}
Some points:
vector::at
when iterating based on i < vec.size()
.Upvotes: 3
Reputation: 415
The problem lies with if(Oscars.at(i).entity.find(input)){
: the std::string::find
will return -1 whenever some text is not found. So if(-1)
will be evaluated to true in the very first entry if the first entry doesn't contain the words to be searched for.
Upvotes: 1