1

In terms of an input file reading,

  • I found

    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.

    for (i=0; inStream >> input[i]; i++ ) ; 
    

    seems to work whether there is a new line or not at the end of file .

    Are there any other neat solution for handling a "new line" at the end of file ?

  • in c, I write

    FILE *fp = fopen("file", "r") ;
    for (i=0; fscanf(fp, "%d", & input[i]) > 0 ; i++ ) ;
    

Are there any way I can use fscanf with c++ input file stream not using fopen() ?

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Jihun P
  • 11
  • 3
  • 1
    Regarding `for (i = 0; !inStream.eof() ; i++) inStream >> input[i];` see [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/) – Remy Lebeau Feb 27 '20 at 02:14

2 Answers2

3

The C++ library provides you with a handy getline function. Here is a minimal example from cplusplus.com

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}
NotNik.
  • 422
  • 3
  • 14
0

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.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108