Reputation: 3
I am a little bit unclear as to how ifstream functions. I have searched, but can't find a specific answer to this question.
What I am trying to do is stop at a certain word, but then do something with the word after that.
Specifically, my program looks through a file containing words. Each time it sees the string "NEWWORD" it needs to do something with the word following "NEWWORD"
string str;
ifstream file;
file.open("wordFile.txt");
while(file >> str){
//Look through the file
if(str == "NEWWORD"){
//Do something with the word following NEWWORD
}
}
file.close;
How can I tell ifstream to go to the next word?
P.S: Sorry if I did anything wrong as far as guidelines and rules. This is my first time posting.
Upvotes: 0
Views: 2577
Reputation: 701
To clarify matt's answer, using >>
on a istream will find the next character that is not a space, and then read in all characters it finds until it reaches a space character or end of file.
Upvotes: 0
Reputation: 14077
Each time you extract from a stream using >>
it automatically advances to the next item (that is how your while
loop keeps advancing through the file until it finds "NEWWORD". You can just extract the next item when you see "NEWWORD":
string str;
ifstream file;
file.open("wordFile.txt");
while(file >> str){
//Look through the file
if(str == "NEWWORD"){
//Do something with the word following NEWWORD
if (file >> str) {
// the word following NEWWORD is now in str
}
}
}
file.close;
Upvotes: 1