0

I've been working on a program that creates and stores information onto files. My only problem that is keeping me from going any farther is the files name. I can manually name the file but I can't use a variable (any would do: number, character anything) for the files name, and for the contents of the file. Here's the 4 lines of code that have driven me up walls for a while now:

ofstream file;
file.open ("txt.txt"); \\I can manually create names, but that's not what I'm after
file.write >> fill; \\I attempted to use a 'char' for this but it gives errors based on the "<<"
file.close(); 

This is my first time using this site. Sorry in advance.

2
  • Sidenote: use // instead for comments in the code. Commented May 9, 2014 at 3:26
  • Sidenote 2: It's just file << fill. You don't need the .write, and the << points TO the file if the output goes TO the file. (It points away file >> when you read FROM the file. You need an ifstream for Input) Commented May 9, 2014 at 8:17

2 Answers 2

1

You may use variables of type strings and ask the user for keyboard input to name your file and fill in contents.

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char** argv) {

    string fileName;
    string contents;

    cout << "What would you like the file name be? : ";
    cin >> fileName;

    cout << "\nPlease write the contents of the file: ";
    cin >> contents;

    ofstream file;
    file.open(fileName.c_str());        // provide the string input as the file name
    if(file.is_open()){ // always check if the program sucessfully opened the file
        file << contents << endl; // write the contents into the file
        file.close();   // always close the file!
    }

    return 0;
}

Note that this program will read input from user for contents until it reaches a newline character '\n' or white space ' '. So if you write HELLO WORLD! as the input for contents, it will only read HELLO.

I'll leave how to read the entire line including whitespaces as exercise for you. I also suggest you grab a C++ book and study file input/output.

Sign up to request clarification or add additional context in comments.

Comments

1

It really depends? C++11 or C++03?

First create a string:

std::string fname = "test.txt";

In C++11, you can just do:

file.open(fname);

However in C++03, you must:

file.open(fname.c_str());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.