Hello Carabus,
Sorry for the delay,
To add to what
Repeater has so nicely said.
As an example:
ifstream in("daata.txt");
. In the first part
ifstream in
this will construct an object of the "ifstream" class and give you a variable to use for your input. The second part
("daata.txt")
uses the overloaded ctor of the class to open the file. Or at least tries to open the file.
There are several reasons why a file will not open. Usually it is because the file name is spelled wrong or the file does not exist in the first place. And as
Repeater said there could be something wrong with the path.
So just because you say
ifstream in("daata.txt");
does not mean the file has
opened.
DO NOT COUNT on this to magically open a file. Or even find the file.
When opening a file for input or output I have found this to be helpful:
1 2 3 4 5 6 7 8 9 10 11
|
const std::string inFileName{ "" }; // <--- Put file name here.
std::ifstream inFile(inFileName);
if (!inFile)
{
std::cerr << "\n File " << std::quoted(inFileName) << " did not open.\n" << std::endl; // <--- "std::quoted" requires header file <iomanip>.
//std::cerr << "\n File \"" << inFileName << "\" did not open.\n" << std::endl;
return 1;
}
|
There is more than 1 way to write line 5, but this is the simplest.
In the if statement there are 2 way to use the output statement. Use whichever 1 you want and comment or delete the other. I would save the whole bit of code somewhere for future use or reference.
An "ofstream" is less likely to have a problem opening a file. First if the file does not exist it will create it, but there are still other reasons that the file could not be open. The directory or subdiretory may not be found, there may be a problem with write permissions, you may have run out of disk space to put the file. And that is what I can remember at the moment.
In you code you have:
1 2 3
|
in.close();
ifstream inn("data.txt");
|
First had you not used "inn" it would have been an error that you are trying to define the same variable a second time. For WIW this is a good place to use a variable for the file name.
Instead of your code you could use:
1 2 3
|
in.clear(): // <--- Resets the stream bits, so it can be used again.
in.seekg(0); // <--- Sets the file point back to the beginning.
|
This makes it easier to reuse what is already set up.
Andy