-
reading from file
hi,
Does anyone know of a way to search a file for certain records and also the record right after the last record you were looking for? k...that probably makes no sense!!
e.g
I want to go through a file like this
dog,1,...
dog,2,...
dog,3,...
cat,2,...
cat,3,...
cat,4,...
so if I was searching for dog, my output should be something like this
dog,1,...
dog,2,...
dog,3,...
cat,2,...
Thanks,
Kings
-
Use getline() to read a line (assuming there is only one entry per line) then make a comparer that compares the first 'word' (the characters until a space or, in your case, a comma is found) with whatever you're searching for. Simply using strcmp() is not good since it will compare the whole line. I guess there are some token comparers available, but none that I know of. I usually write that stuff myself :).
-
assuming file is comma delimited as it appears and each line of file has same number of elements, then you can do something like this:
Code:
1)set up flag to be false
2) use loop to read in first string from a line in file using the comma as a delimeter for either get() or getline() depending on your needs.
a) compare first string of each line as it is read in for the desired data using strcmp() or one of it's cohorts if using C style strings or equal operator if using STL strings.
b) if current string is desired value
i) use loop to read in all subsequent strings on this line
ii) set flag to true
c) else if current string isn't desired value and flag is false
i) use loop to read all subsequent strings but ignore them
d) else if current string isn't desired value and flag is true
i) use loop to read in all subsequent strings on this line
ii) set flag to false