I am trying to write to a .txt
file within a program, and I am using the following code snippet. I want to output a line of the form:
a(space)b
but I get nothing on the txt file.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(){
string a = "string";
int b = 0;
fstream f;
f.open("filename.txt",ios::in | ios::out );
f << a << ' ' << b << endl;
f.close();
return 0;
}
CodePudding user response:
If you try this piece of code:
f.open("filename.txt", ios::in | ios::out);
if (!f.is_open()) {
cout << "error";
}
you will see that the file is never opened. ios::in
requires an already existing file (
It should work if you should only pass std::ios::out
to f.open()
:
f.open("filename.txt", ios::out);
Read here why you shouldn't be using namespace std;
.
CodePudding user response:
Try this version. Few changes:
- Include the correct header
<string>
instead of<cstring>
- No
using namespace std;
- Use
std::ofstream
for output - No
.open()
: pass the filename in the constructor - Check if the file is valid after opening
- No
.close()
. Let the destructor do its job. - No
std::endl
if'\n'
is enough.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string a = "string";
int b = 0;
std::ofstream f("filename.txt");
if (!f) {
return EXIT_FAILURE;
}
f << a << ' ' << b << '\n';
return EXIT_SUCCESS;
}