Text File Binary Search

做~自己de王妃 提交于 2019-12-06 15:33:22

LineNumbers is being modified by your loop going from 4, to 1, to -1. The -1 makes your loop terminate too early so you don't pick up the first entry properly.

It seems like a homework problem, so I hope you can use this to direct yourself towards an answer.

When using functions such as seekg, it is always best to open the file in binary mode, not text mode as your code is doing now. In other words, you should be doing this:

cardNumbers.open(fileName, std::ios::in | std::ios::binary);

The reason is that opening a file in text mode will allow end-of-line translations to be done. This renders functions such as seekg, tellg, etc. anything between unstable (or lucky to work) at best, and in the worst case, useless for text processing.

When a file is opened in binary mode, the seekg and other family of functions work as expected, since there are no end-of-line translations being done. You will actually seek to the byte offset in the file that you specify, and not be thrown off by end-of-line translations.

Also, once you do this, the length of the data in the line includes not only the visible text, but also the invisible characters that make up the end-of-line sequence. So your hand calculation of 57 is not going to be correct in binary mode -- it should be 58 or 59, depending on whether you are using Linux / Unix, or Windows, respectively.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!