Sign in to follow this  

asking user for file to open with ifstream or ofstream?

This topic is 3491 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I am writing a program to read from a file. I want to ask the user for the file name to open. I have tried to use the basic open file code from cplusplus.com and it won't work unless I specify the file name in the code. If I have them enter a file name, I then need to add "'s to it? Either way, I get errors if I use char or string for the input file name. Can anyone show me how to do this? Code from cplusplus.com with my variable for the fileName: #include <iostream> #include <fstream> using namespace std; int main () { char fileName[256]; cout << "Enter a file"; cin >> fileName; //tried string instead of char with getline(cin, fileName) //but same problem as below. ofstream myfile; myfile.open (fileName); //should have quotes around the file name // ex. ("file.text") // but how to put //them in? Won't let me concatenate them in myfile << "Writing this to a file.\n"; myfile.close(); return 0; } Thanks for any help understanding this. I have heard that it is best to use this method for open and close because it is explicit so if I can make it work this way, I would prefer it.

Share this post


Link to post
Share on other sites
Code works fine for me..

Asks me to enter a filename, i type in

test.txt

and that file is created, with the "Writing this to a file." line in it

You don't need to add quotation marks to the filename. You only need to do that when you're passing in a hard coded file name to myfile.open.

eg, myfile.open(file.txt) wont work because the compiler doesn't know what file.txt is.. but doing myfile.open("file.txt") tells it to treat file.txt as a string.

As you're currently doing it, you've got fileName defined as a char array, so the .open function is happy as it can 'tell' you're passing the correct parameter type to it.

Sorry, i'm pretty awful at explaining things properly..

Share this post


Link to post
Share on other sites
sorry, I was getting all kinds of errors for other things like the concantination I was trying to do so it had me confused. I tried starting fresh and not useing the quotes and it works.

Thanks for the reply.

Share this post


Link to post
Share on other sites

This topic is 3491 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this