Adding a file type

Hi guys Im trying to create a program where you can create a simple text file automatically after entering the name using fstream. Its for a system Im gonna work on and its crucial for me to succesfully do this since this is where all of it revolves.
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream.h>
#include <fstream.h>

int main () {
char file [16];
cout<<"Enter text file: ";
cin>>file;
ofstream newFile();
newFile.open(file+".txt");
newFile.close();
return 0;
}


It says invalid use of addition or something. Is there any way to concat a ".txt" into the end of the file? Any help would be nice. Im only just learning all of this so I would appreciate any help and tips given.
Last edited on
First the header files ending in .h are not standard C++. The code should look something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
#include <cstring> // for strcat

using namespace std;

int main () 
{
    char file [80];
    cout << "Enter text file: ";
    cin >> file;
    strcat(file, ".txt");
    ofstream newFile(file);

    newFile.close();
    return 0;
}


or rather safer, using C++ std::string instead of a character array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
#include <string> // for std::string

using namespace std;

int main () 
{
    string file;
    cout << "Enter text file: ";
    cin >> file;
    file +=  ".txt";
    ofstream newFile(file.c_str());

    newFile.close();
    return 0;
}
Last edited on
For some reason my code doesnt work if im not adding .h in the header files. Im using turbo c. Is there any difference with turbo c and c++? Btw I really appreciate your help. Ill try it as soon as I can.
If you can possibly avoid it, don't use turbo c. It is extremely old and uses a non-standard (and buggy) dialect of the language. (I'm aware that some educational courses recommend it, which is unfortunate, as you will later have to un-learn some things).

Something like code::blocks would be better. http://www.codeblocks.org/
Its kinda the only available compiler at my school where I make the codes since I broke my laptop lol. So i have no choice but to use it.
Topic archived. No new replies allowed.