Hi people, i was trying this program while understanding the basics of input/output a txt file.
SO this is a program while asks the user to input the name of the text file.
If it exists, then it will read it else, it will create it and it will prompt the user for some input. Thereafter, it will read the same file again...
here is the code:

#include<fstream.h>
#include<iostream.h>
#include<string.h>
#include<conio.h>
using namespace std;
int main()
{
    char a[34];
    string line;
    do{
    cin.getline(a, 34);
    ifstream tanmay;
    tanmay.open(a);
    if(tanmay.is_open())
    {
                        while(!tanmay.eof())
                        {
                                            getline(tanmay, line);
                                            cout<<line<<endl;
                                            }
                        }

                        else 
                        {
                             ofstream tammy;
                             tammy.open(a);
                             cout<<"input something\n";
                             string line2;
                             cin>>line2;
                             tammy<<line2;
                             tammy.close();
                         }
                         }
                         while(!tanmay.is_open());
 getch();
 return 0;   
}

But after compiling, i am getting an error of keeping- tanmay as undeclared..
But, if i am right, i have already declared tanmay.
So can you tell me where i am wrong?
THANKS A LOT ...

tanmay exists INSIDE your do-while loop, but you're trying to check for it being open OUTSIDE while(!tanmay.is_open());

Also, you're using a very old C++ compiler and not doing yourself any favours. You can get a new, modern one for free.

Also, the way you're using eof( ) can lead to incorrect results.

When you first test it, before attempting to read from the filestream, eof( ) has no real meanning. It's not until you attemtp to read past the end of the file that eof( ) will true. If the file is in fact empty, you'll enter the processing loop, read (nothing) and do your processing of that non-input.

If you're fixated on using eof(), you should attemtp to read once outside the loop (priming read), then put a read attempt at the end of the loop body.

fin >> data;
while( !fin.eof( )
{
    //do stuff with data
    fin >> data; //get the next item
}

To avoid duplicating your input statemment, you can place it as the condition for the while loop.

while( fin >> data )
{
    //do stuff with data
}
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.