any way I can use fscanf
with c++ input file stream?
Possibly. Both g++
and Visual Studio have had their own extenstions making it possible. If you find such possibilities, they are non-standard and not portable. I advice you to find other ways.
If you use C++, try to use the most of it. C
does have fscanf
which looks neat - but it's a beast. C++ has std::scanf
for portability - and it's the same kind of beast. Don't use it if you are programming C++.
The problem you're trying to avoid
for (i = 0; !inStream.eof() ; i++) inStream >> input[i];
tries to read one more time if there is a "new line" at the end of file.
is caused by improper use of eof()
. eof()
returns true
after you've tried to read beyond end of file. A better loop would look like:
for (i = 0; inStream >> input[i] ; i++);
Notice how the extraction and condition became one? They aren't. The extraction happens first and returns the stream used in the extraction. The stream has a bool
overload that tells you if it's in a failed state or not, making it great for this kind of checking: if(stream >> variable) { /* success */ } else { /* fail */ }
.
This only works if your array has entries enough to store all input though. Your loop does not check that. If you use a vector
you can just read elements and push_back
to make it work a long long time. If you have a fixed (relatively small) size and do the above, it'll fail eventually.