Hi guys, I am new to C++ and I have created a simple program that opens a text file and then displays its contents. For this program I have also developed a menu but I was trying to create an option so that I could enter the name of a text file and then it would open it as a new file and display the contents of it. Although I can't figure out how to do this, any advice would be great.
Thanks and happy new year!
Write the code for what you know so far - and then we can help you fill in the blanks.
If you know how to work with strings, you can input a string containing the name of a file, and then supply this string as the name of the to create, if that helps.
Hi, thanks for your reply. I have not used strings yet although I have used char arrays. Is the string method you mentioned the best way to do this?
Either one would work. You should generally prefer to use the C++ string class for C++ programs, so technically that is the better way. Regardless, you should create a variable to hold the user input, then pass that value to the file stream constructor or open function where you are currently putting the file name.
Do you mean something like the following code?
ifstream b ("a")
char a; // max path in MS-Windows and I think *nix is 255 characters
cin.getline(a,sizeof(a)); // allows input if spaces
ifstream b (a); // no quotes
>> Do you mean something like the following code?
With Ancient Dragon's corrections that code will work just fine, although you aren't using C++ strings, you are using C style character arrays. Since either will work, it is up to you to choose, although like I said earlier C++ strings are generally perferred in C++ programs.