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:

using namespace std;
int main()
    char a[34];
    string line;
    cin.getline(a, 34);
    ifstream tanmay;
                                            getline(tanmay, line);

                             ofstream tammy;
                             cout<<"input something\n";
                             string line2;
 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?

Recommended Answers

All 2 Replies

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, learning, and sharing knowledge.