Home > Mobile >  Syntax misunderstanding and confusion
Syntax misunderstanding and confusion

Time:09-30

I am trying to read a file and also try the Gauss elimination process. One thing that is unclear to me is the syntax of the ifstream, when you want to read a file. In on previous example the syntax was like this:

ifstream filein;
filein.open(Filename=name of the file I will read from)
if(not filein.good()){
cout <<"There's seems to be a problem";
exit(1);

Then in my current exercise the following is written:

ifstream dfile(fname=name of the file I will read from) ;
if( not dfile)
{
cout <<"There seems to be a problem";
exit(1);
}

In both cases we are trying to read what is in the file, now my questions are:

1 - Why aren't the code sequences the same since the same things is being done, meaning we are reading from a file?

2 - In the beginning we have file.open and in the other program we don't. Then we see filein in the first one and dfile in the next one. I tried google to find out what is the meaning of them but I got no results. Can someone explain to me how this reading/writing thing works? In our classes the professor didn't took the time to do so.

CodePudding user response:

The code isn't the same because... there is almost always more than one way to write a program. The two examples are showing different approaches.

The first case uses the default constructor to create an ifstream object which, by default, doesn't open a file. Then, the ifstream::open() method is called to open a file. Finally, the method ifstream::good() is called to see if the file was opened successfully.

In the second case, a non-default constructor is used to initialize the ifstream object with the name of the file to read, and a different test is used. The not operator takes an operand of type bool, and so the compiler first calls the operator bool defined for ifstream to convert the object into a bool, which is used to determine whether a problem was encountered.

Note that, because there are various states that a file stream can in (for example, no file was found, or it couldn't be opened, or it was opened but we got to the end of it), these methods aren't necessarily going to give the same results.

There's more on this here: http://www.cplusplus.com/reference/fstream/ifstream/?kw=ifstream

CodePudding user response:

The problem is probably in you using if stream file in instead of ifstream filein.

  •  Tags:  
  • c
  • Related