Problem:
In your file the strings aren't separated by a space (' '
) which is the end delimiter, they are separated by a end of line ('\n'
), that is a different character. As a consequence, in the first getline
everything goes to line
. line
contains all the text in the file, including z's, so all the content is printed. Finally, the code exits the while
block after running once because getline
reaches the end of the file and fails.
If you run this code
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string line;
std::ifstream infile;
infile.open("words.txt");
while(getline(infile, line,' ')){
std::cout << "Hi";
if(line.find('z')){
std::cout << line;
}
}
}
"Hi" will be only printed once. That is because the while
block is only executed once.
Additionaly, see that line.find('z')
won't return 0 if not match is found, it will return npos
. See it running this code (As it says here):
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string line;
std::ifstream infile;
infile.open("words.txt");
while(getline(infile,line)){
std::cout << line.find('z');
if(line.find('z')){
std::cout << line << "\n";
}
}
}
Solution:
Use getline(infile,line)
that is more suitable for this case and replace if(line.find('z'))
with if(line.find('z') != line.npos)
.
while(getline(infile,line)){
if(line.find('z') != line.npos){
std::cout << line << "\n";
}
}
If you need to put more than one string per line you can use the operator >>
of ifstream
.
Additional information:
- Note that the code you posted won't compile because
string
, cout
and ifstream
are in the namespace std
. Probably it was a part of a longer file where you were using using namespace std;
. If that is the case, consider that it is a bad practice (More info here).
Full code:
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string line;
std::ifstream infile;
infile.open("words.txt");
while(getline(infile,line)){
if(line.find('z') != line.npos){
std::cout << line << "\n";
}
}
}