-1

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;
}
     
Costantino Grana
  • 3,132
  • 1
  • 15
  • 35
ten1o
  • 165
  • 5
  • You might taking loot at another file filename.txt. – 273K Nov 25 '22 at 18:19
  • 1
    If the file does not exist, and you try to open it for reading (`ios::in`), it should [fail](https://en.cppreference.com/w/cpp/io/basic_filebuf/open). Have you tried opening the file just for writing (`ios::out`)? – rturrado Nov 25 '22 at 18:22
  • Probably you also want to `#include ` instead of the C one. This doesn't event compile under Visual Studio. – Costantino Grana Nov 25 '22 at 18:27
  • @rturrado but the file already exists. – ten1o Nov 25 '22 at 18:53

2 Answers2

2

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 (std::fstream::open()):

enter image description here


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;.

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
0

Try this version. Few changes:

  1. Include the correct header <string> instead of <cstring>
  2. No using namespace std;
  3. Use std::ofstream for output
  4. No .open(): pass the filename in the constructor
  5. Check if the file is valid after opening
  6. No .close(). Let the destructor do its job.
  7. 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;
}
Costantino Grana
  • 3,132
  • 1
  • 15
  • 35