hello
i'm trying to write and read a vector of strings to/from a text file. it should count how many lines contain the word "here". but it does nothing.
Why are you using write() when using text mode? You probably should be using the insertion operator<< instead since you seem to expect each element of the vector to be on it's own line and you're not writing any new line characters to the stream. When you think you're writing "here" you're also writing a bunch of junk since you're writing more characters than the string contains.
Really your write() function should probably look more like:
I'm not sure how exactly std::vector stores its data, but that method of writing its contents looks really bad
changing line 7 to for(size_t i = 0; i < vetor.size(); i++) file << vetor[i] << '\n';
works fine
you should never assume anything about any data structure or class provided by an external library (i.e. which you didn't write), since it may change depending on the platform or version, use the provided interfaces and functions.
I'm sure there is better ways to write to a file, mostly for performance reasons, but for a little test the above one works just fine.
There's also a problem with the while loop in function readTextFile().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void readTextFile(){
std::vector<std::string> vetor;
std::string line;
std::ifstream file("text.data");
int n = 0;
int m = 0;
while (file.good()){
std::getline(file, line);
if (line.find("here")!=std::string::npos) {
n++;
// std::cout << "found " << n << std::endl;
}
else
m++;
}
std::cout << "n = " << n << " m = " << m << '\n';
}
I temporarily commented out line 11 - purely to reduce the quantity of output generated.
Here is the output (assuming the file generate problem has been corrected as mentioned above):
n = 2000 m = 8001
Notice the second value is 8001 but it should be 8000 (so that m + n == 10000).
The problem is, the loop condition file.good() says what happened to the previous read. It does not predict whether the next getline will succeed.
Instead put the read operation as the loop condition, that way the body of the loop is processed only after a successful read :
7 8 9 10 11 12 13 14
while (std::getline(file, line)) {
if (line.find("here")!=std::string::npos) {
n++;
// std::cout << "found " << n << std::endl;
}
else
m++;
}