text file name

I need to enter only the name of a user and automatically put ".txt" in the end of the name to create a text archive without the need of the user to write the ".txt" in the end;
something like that:
string name;
cin >> name;
ofstream user(name.c_str());//but add the .txt in the end
Last edited on
What have you tried? You're using a std::string so you can just "add" the desired extension to the end of the string.

By the way if you are compiling for one of the current C++ standards (C++11, C++14) you shouldn't need to use c_str() any longer for the stream constructors.

Try this: name += ".txt"; :) after cin >> name;
Last edited on
There are lots of ways to do this.
The most direct would be
ofstream user( (name + ".txt").c_str() );

or if that seems hard to read,
you might do
string filename = name + ".txt";
ofstream user(filename.c_str());

Also a modern C++ compiler (in C++11 mode or later) should accept a std::string without the .c_str()
ofstream user(filename);

Thanks everyone! It worked!
Topic archived. No new replies allowed.