Asking for Filename from user!

Hey guys! I wanted some help on filenaming! I wanted the user to input the filename. Also if he could also input the file extension, it would be good. Mostly, I need the text file.
Please write your codes in C++. Any help would be appreciated. Thanks! :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    string date;
    cout<<"Enter date: ";
    getline(cin,date);
    cout<<endl;
    string title;
    cout<<"Enter note title: ";
    getline(cin,title);
    cout<<endl;
    string note;
    cout<<"Enter note: ";
    getline(cin,note);

    ofstream diary;
    diary.open("date.txt",ios::out);
    if (!diary)
        cout<<"Error opening file!";
    else
    {
        diary<<date<<"\n\n"<<title<<"\n"<<note;
    }
    return 0;
}
Read the filename as you have done with the other strings and pass it to the open function.
Didn't get your point! Can you elaborate it please? Thanks!
The open on line 21 takes char array as it's first argument.

Simply prompt the use for a filename.
Read it into a char array, then pass the char array to open instead of the quoted literal.
The open on line 21 takes char array as it's first argument.
Use C++11 compiler and use std::string without need to use unsafe c-strings ever again.

1
2
3
4
5
std::cout << "Enter name of file to open: ";
std::string filename;
std::getline(std::cin, filename);
ofstream diary;
diary.open(filename, ios::out);// or filename.c_str() if you have old compiler 
Last edited on
Do you mean something like this?

1
2
3
4
5
6
char file[50];
cout<<"Enter filename: ";
cin>>file;

ofstream diary;
diary.open(file);
@MiiNiPaa, the code you suggested gave some huge errors! :(
Post exact error here. Did you try to use filename.c_str() an suggested in comment?
What compiler do you use?
Last edited on
This was the error!

error: no matching function for call to 'std::basic_ofstream<char>::open(std::string&, const openmode&)'|

And I use CodeBlock.
Okay the .c_str() thing worked!! Thanks a lot! Now I am facing a new probelm! It just creates a file with that name! I want it to be a text file! What do I do? Thanks again!!
ios::out presumes that it should overwrite this file.
Either use ios::app or ios::out|ios:ate (if you want to use seekg())

Select settings → Compiler and debugger → in compiler flags set "Have g++ follow upcoming C++0x ISO..."
And after that first example will work too.
Last edited on
Thanks! That worked too! :D
I know this is going somewhere else but can you tell me how to use system's date and time so that I won't have to ask for it from the user?
Last edited on
Topic archived. No new replies allowed.