Robert E Robert E - 1 month ago 6
C++ Question

How to get a certain word in string of getline?

How can someone get only a certain word in a string of a getline method? For example:

Test.txt:

hi guys
im @@Paul \t\t [GET THIS]





string line;
string word;
ifstream file ("test.txt");

if (file.is_open()) {
while (getline(file, line)) {
if (line.find("@@Paul") != string::npos) {
strcpy(word, line.c_str());
}
}
}


How can I code it so when I find
@@Paul
it only takes the characters (
[GET THIS]
) after the double tab (
\t\t
)?

Answer

this is definition of getline function: istream& getline (istream& is, string& str, char delim);

Delim is a delimitier which stops getline from reading the stream after to the given character. so you can do something like this:

string trash;
string properline;

getline(file, trash, '\t');
getline(file, trash, '\t'); //second tab, still trash
getline(file, properline);
Comments