Thread: how do u read in from file using a class...I want user to enter name of filetopoen

  1. #1
    sexygir25
    Guest

    how do u read in from file using a class...I want user to enter name of filetopoen

    class readinfile {
    public:
    readinfile(char * file) //Opens file and read information
    {
    file = "file.txt";
    ifstream infile;
    infile.open(file);
    char linein[80];
    cout<<"\nPlease enter the input file name \n(need including the file extention): ";
    cin>>file;
    if (!infile)
    {
    cout<<"no cant open";

    }

    while (infile.peek()!=EOF)
    {
    infile.getline(linein,79);
    cout<<linein<<endl;
    }
    cout<<endl;

    infile.close();


    }


    private: char *fp;








    };

    #endif

    //hello..how do u enable user to enter name of file he or she wants to open and print out characters

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Code:
    readinfile(char * file) //Opens file and read information
    {
    file = "file.txt";
    Why send a parameter that you change and never use?

    Try this basic layout. I think it's nicer layout if you put the cin in main instead of the constructor, and using a method instead of the constructor to open the file (so you can control when it's opened, not just when the object is created. If you do want it to open at startup, call it in the constructor):
    Code:
    class ReadClass
    {
       public:
          bool ReadFile(const char* FileName);
    };
    
    ReadClass::ReadFile(const char* FileName)
    {
       ifstream File;
       File.open(FileName, ios::in);
    
       if(File.fail()) return false;
       
    
       //*** Do reading operatons here ***
    
    
       File.close();
       return true;
    }
    
    int main()
    {
       ReadClass MyClass;
       char FileNameBuffer[64];
    
       cin >> FileNameBuffer;
    
       MyClass.ReadFile(FileNameBuffer);
    
       return 0;
    }
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Totally confused on assigment using linked lists
    By Uchihanokonoha in forum C++ Programming
    Replies: 8
    Last Post: 01-05-2008, 04:49 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  5. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM