0
What is estr() function in File Handling in C++ used for??
Int main { fstream file; string word,filename; filename="1.txt"; file.open(filename.estr()); while(file>>word) cout<<word; }
4 Respostas
+ 1
fstream::open takes a filepath argument as a 'const char*' and tries to open it. The argument in your example is simply the value of 'filename' ("example1.txt").
So the statement tries to open the file at "filename" (which is "example1.txt" in this case) and associates it with the "file" object.
3 things to note, though:
1. Since (i assume, based on the example) you're only reading from the file, and not writing to it, you should use 'ifstream' instead of 'fstream'. See https://stackoverflow.com/questions/30388453/ifstream-and-ofstream-or-fstream-using-in-and-out
2. The parametrized constructor of 'fstream' does actually open the file, so the call to 'open' is redundant and should be removed.
3. You should check if the file was opened successfully before trying to manipulate it. This can be done like so:
if (!file) {
// Handle error. Possibly return from the function/exit the program
}
else {
// File was opened successfully.
}
The 'else' isn't necessary if you return/exit in case of an error.
+ 2
There is no "estr()" function in std::string. Are you sure it's not "c_str()" that you're talking about? If it is, then "c_str()" returns a pointer to the std::string's underlying data as a C-String (const char*).
std::string str = "foo";
const char* cstr = str.c_str();
bool isEqual = strcmp(cstr, "foo") == 0; // true
0
Isho #include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
fstream file ("Desktop\example1.txt");
string word,filename;
filename="example1.txt";
file.open(filename.c_str());
while(file>>word)
{
cout<<word;
}
}
Yes you're right it was c_str()
Now i just wanna understand about the line right above the While loop, what is that line doing? Can you please explain?
0
Isho Thankyousomuch, yes understood!