welcome everybody, i am able read my file by asking the filename from user but i am facing a little problem,When i type a name of file which doesnot exist,compiler also shows it with some zeroes, this is my program, please help me,having problem in case 2...

#include <fstream>
#include <iostream>
#include<stdlib.h>
using namespace std;
char ch;
int main()

{


    char name[1000];
    char lname[1000];

    long Age;
    int choice;
    char FileName[50]="Filename.txt";
      fstream students;

 while(1)
 {
    system("cls");
    cout<<"*1*\tCreate a file\t\n";
    cout<<"*2\tOpen the File\t\n";

    cout<<"*3*\tExit the Programme\t\n";
    cout<<"\n\n"<<endl;
    cout<<"Enter your choice\n"<<endl;
    cin>>choice;
    system("cls");
    switch(choice)

    {


    case 1:
    {
      cout << "Enter First Name: "<<endl;

    cin>>name;

    cout << "Enter Last Name:  "<<endl;

    cin>>lname;

    cout << "Enter Age : "<<endl;

    cin>>Age;



    cout << "\nEnter the name of the file you want to create: "<<endl;

    cin >> FileName;

    ofstream students;
    students.open(FileName, ios::app);

    students << name << "\n"<< lname << "\n" << Age<<endl;
    students.close();
    break;
    }



    case 2:


    {

    ifstream rstudents;
    cout<<"FileName = "<<endl;
    cin>>FileName;

    rstudents.open(FileName);


    {
        rstudents>>name;
        rstudents>>lname;
        rstudents>>Age;


    cout << "\nFirst Name: " << name;
    cout<<"\nlast name: "<<lname;

    cout << "\n Age:  " << Age;
    }
    students.close();


    }

    case 3:
    {
        cout<<"\nGood Bye"<<endl;
        system("pause");
        exit(0);
    }


}


}


}

When you open a file to read from it, then it will not open successfully if the file does not exist. You can check if the file has been opened successfully with the is_open() function, like this:

if( rstudents.is_open() )

which you could use in a loop like this:

while( !rstudents.is_open() ) {
    cout << "FileName = " << endl;
    cin >> FileName;
    rstudents.open(FileName);
};

to which you could also add an error message to tell the user that the file (probably) didn't exist (I say 'probably' because there could be another reasons why a file cannot be opened, but those are rare).

Also, it is generally a good idea to check that a stream is in a good state, which you can simply do with something like if( !rstudents ) which will check if the rstudents stream is in a bad state (not good), such as having reached the end of the file or having failed to do the last read-operation, for whatever reason.

Also, the C++ standard header for the C stdlib.h header is cstdlib, as in #include <cstdlib>.

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.