i got a nice task. I've got it figured out pretty much, but i already know that this approach is so cumbersome that i won't even post it. There must be such an easy way that i just cant figure it out.
So here's the deal. I've got a longer file which contains data. I am searching for a specific triggering word that is only contained in the file once like "bananas". In the next line there is a tab spaced table that i want to write into an array. Thats basically it.
What i did was: 1) skim through the lines with fgets 2) compare with strcmp if 'banana' is hit 3) break the while 4) march to the next while going to the end 5) reading all information to an array.
Sounds complicated to me, so there must be a super easy way.
Thanks for your help, really appreciate it! You guys are always awesome!
If you use std::string rather than C style strings and strcmp, it would make handling strings more intuitive. You could compare them just with '=='. http://cplusplus.com/reference/string/string/
Well that's a pain, but ah well... I don't see that there'd be a way to do it other than reading through the file until you find the word you want. Your method seems sound to me.
There are of course various ways you could handle it: loading the whole file at once and parsing it in memory, or parsing it as a filestream as you go. However, these should only matter if performance is an issue.
I'm not particularly familiar with C style functions for this purpose, but looking at the documentation pages on this site for those functions, your code seems fine. Clearly, you have to put appropriate code in place of your comment.
One problem you may encounter is allocating this array. You do not know in advance how many elements are read from the file, and thus how many elements you need in the array. One approach would be to make a top estimate of the number of entries and allocate that many array elements.
Hope this helps.
PS: If this is the code you thought was "cumbersome", then do not worry - it seems reasonably simple to me :)
The problem that you were mentioning is key to running this baby without a crash. Since it has to be more than stable in the environment that it's going to run allocation is important. I've got an companion header file that explicitly gives away the number of array elements, therefore the array can be allocated just in the right amount with