i want the user to enter the name of the file to open and i want it in c++, i have seen a similr work done in vc but i m nt abl 2 implement da same in c++

Recommended Answers

All 19 Replies

Could you post your own try first?

[char name[100];
ifstream infile;
cout<<"Enter filename>>";
gets(name);
infile.open(name);]

this is my code segment that is not working. i suppose i am missing something

I'm going to give you the code.
You're going to study it :)

#include <iostream>
using namespace std;

int main( ) {
    cout << "Please enter a file name: \n";
    string name;
    cin >> name;
    ifstream ist(name.c_str( )); //c style strings are required by some system interfaces
    if(!ist) cerr << "Can't open file!\n"; // if the file failed to open
    cin.clear();
    cin.get();
}

This doesn't actully do anything with the file, but it opens the file that the user requests.

I havn't tested it, so you might have to fix it up. Have fun! :)

thank you for the code but my compiler does not accept 'string' data type

Just use char then

can you please tell me what the last 2 lines of the code are there for?

cin.clear() is for throwing away 'enter' (the button you pressed to enter the file name)

cin.get() is to tell it to wait for the user to press enter to close the window.

just ask away if you have any more questions :)

Tomtelaw, you forgot to add the following line to your code: #include <string> :P

tux4life, it's included in <iostream> .... I think :P

EDIT: Woops, you're right lol sorry

thank you both of you.
I will implement this and disturb you again if i have anymore problems:)

You might also want to prompt the user for the file's path. This way, you'll have a second variable, or you'll have to also tell the user to include the path when he inputs the file name. If you go for the former, you'll also need some string concatentation.

To start: a foreword on the use of gets()

char name[100];
ifstream infile;
cout<<"Enter filename>>";
gets(name);
infile.open(name);

this is my code segment that is not working. i suppose i am missing something

Damn, how could I have overlooked this: gets(name); To the OP, and everyone else who still uses gets to get user input: don't use it anymore, C++ has a beautiful I/O class library which doesn't have the 'bad things' which the gets() function has.
gets() can just allow an array overrun, what if the user enters more than 100 characters ?
Remember that gets() isn't very intelligent, and it will act in a very bad way then: it will just start writing in some memory which doesn't belong to your program anymore, on modern OSes, you have luck, and the OS will be able to prevent the program from damaging and messing up the whole thing, but if your OS doesn't offer memory protection for example, your program will be able to crash the whole operating system if the user would enter more than 100 characters.
In C++ you could for example do: cin.getline(name, 100); or cin >> setw(100) >> name; (but you'll have to include the iomanip header if you want to use the setw manipulator to lock the upper limit so that cin won't overflow the array)
But just to make it yourself easy, use the string class to store user input, you don't have to worry about array overflows then:

#include <iostream>
#include <string>
using namespace std;

int main()
{
   string user_input;
   cout << "Enter some text: ";
   getline(cin, user_input); // immediately get a whole line
   cout << "You entered: " << user_input << endl;
}

Reading a file name from the user
But for filenames, only the first entered word is enough so it would probably better to read the filename like this:

#include <iostream>
#include <string>
using namespace std;

int main()
{
   string filename;
   cout << "Enter the filename: ";
   cin >> filename;
   cout << "The filename you entered was: " << filename << endl;
}

Adding an ifstream object to your code:
Now you can successfully read the filename from the user, you can start adding other things to your code, things like opening the file with the filename the user entered.
(I assume you only want to open it for reading)
First you'll need to create an ifstream object:

#include <iostream>
#include <fstream> // new line of code
#include <string>
using namespace std;

int main()
{
   string filename;
   ifstream infile; // new line of code
   
   cout << "Enter the filename: ";
   cin >> filename;
   cout << "The filename you entered was: " << filename << endl;
}

Now the only thing left is opening the file, checking whether the file was opened correctly, and start reading it.

Opening the file:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
   string filename;
   ifstream infile;
   
   cout << "Enter the filename: ";
   cin >> filename;
   cout << "The filename you entered was: " << filename << endl;
   
   infile.open( filename.c_str() ); // new line of code
}

As you can see I've added the following line: infile.open( filename.c_str() ); You probably already know that the open() method is for opening the file, but what else do we use?
We also use the c_str() method from the string class, to convert the filename entered by the user to a constant character string.
Why do we need to convert it to a constant ... ?
You need to convert it because the open() method only accepts character strings, it won't accept the C++ string we have in our program (without conversion).

Check whether the file has been opened successfully:
Before you start reading from the file, you need to include a check to see whether the file has been opened successfully, imagine that you try reading from a file which couldn't be opened?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
   string filename;
   ifstream infile;
   
   cout << "Enter the filename: ";
   cin >> filename;
   cout << "The filename you entered was: " << filename << endl;
   
   infile.open( filename.c_str() );
   
   // Check whether the file was opened successfully:
   if( !infile.is_open() )
   {
      // If the file couldn't be opened:
      cout << "File couldn't be opened successfully!" << endl;
      return 1;
   }
   
   /*
         Add your other code to read from the file here
   */
}

Start reading from the file
This part is up to you :P

commented: Proff. Tux teaching. +7
commented: A cookie for the effort :) +22
commented: good +7

tux4life,
I appreciate your time. I guess, from the OP's post that he/she has old compiler.
>include string.
-- is unnecessary when we include iostream and imports std namespace.

tux4life,
I appreciate your time. I guess, from the OP's post that he/she has old compiler.
>include string.
-- is unnecessary when we include iostream and imports std namespace.

Well, to be honest I've never used an old compiler, so I couldn't know that, but I guess you're right.
(Hey OP, do you use an old compiler? Then I strongly want to suggest you to get a decent compiler, or: why not directly get a decent IDE: Code::Blocks for example; If you are using a modern compiler, then you may ignore this. (Please note that Turbo C or Turbo C++ are not categorized under modern compilers))

cin.clear() is for throwing away 'enter' (the button you pressed to enter the file name)

Uh?? cin.clear() is used to set error state flags.
And...What has the ENTER-key to do with this?

thank you for the code but my compiler does not accept 'string' data type

What dinosaur compiler are you using?
Wait, I guess: Turbo CrapCompiler++ (yes, that's it's full name :P)

In that case there's probably no other way around than just using character arrays.

But the best thing you could do is: get a decent compiler.

Yes I know they are old compilers but I am supposed to use C++.
Thank you tux4life and all other people. Your guidance has been alot of help. The problem now at hand is that I also want the user to specify the file path. 23.12.2012 has said something related to that but I do not get it.
Other problems that appear are:
=>when i write: infile.open(filename.c_str()), an error occurs saying: "Structure required on left side of . or .*

=>when i write: if(!infile.is_open()), an error occurs saying: " 'is_open' is not a member of 'ifstream'.

what to do now?

>what to do now?
I'm not familiar with old compilers, so I really have no idea.
Have you tried to use old style headers, for example: #include <fstream.h> instead of #include <fstream> ?

yes I am using the same

Member Avatar for iamthwee

Well if you're using the antiquated version of Turbo C, it probably won't like std::string .

My immediate advice would be to pretend you're writing this in c. However, your professor is probably expecting some bastardized version of c++ and c.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.