سؤال

here's a part from my code

string word;
cin >> word;
string keyword;
while (file >> keyword && keyword != word){}

This searches for a word in a file and if it finds that word (keyword) then it starts a string from there later. It's working perfectly at the moment. My problem is that when the line is

"Julia","2 Om.","KA","1 Om. 4:2"

if I enter word Julia I can not find it and use it for my purposes (just FYI I'm counting it). It works if I search for "Julia","2 since this is where space comes in.

I'd like to know how can I change line

while (file >> keyword && keyword != word){}

so I can see when the text/string CONTAINS that string since at the moment it only finds and accepts it if I enter the WHOLE string perfectly.

EDIT: Also what I have found this far is only strstr, strtok, strcmp. But these fit more with printf than with cout.

هل كانت مفيدة؟

المحلول 2

The problem is that you're extracting strings, which by default will extract up until the next space. So at the first iteration, keyword is "Julia","2. If you want to extract everything separated by commas, I suggest using std::getline with , as the delimeter:

while (std::getline(file, keyword, ','))

This will look through all of the quoted strings. Now you can use std::string::find to determine if the input word is found within that quoted string:

while (std::getline(file, keyword, ',') &&
       keyword.find(word) == std::string::npos)

Now this will loop through each quoted string until it gets to the one that contains word.

نصائح أخرى

You can use methods from std::string like find.

#include <string>
#include <iostream>
// ...
std::string keyword;
std::string word;

getline(file, keyword);
do
{
    std::cin >> word;
}
while (keyword.find(word) == std::string::npos);

Use this method of istream to get a whole line instead of just a single "word":

http://www.cplusplus.com/reference/istream/istream/getline/

Then use strstr, to find the location of a string (like Julia) in a string (the line of the file):

http://www.cplusplus.com/reference/cstring/strstr/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top