Noob.Alone.Programmer
Noob.Alone.Programmer

Reputation: 125

c++ File Handling error: Write and Read from same file and same program

I am trying to write and read from a file in the same cpp program, but i am getting 3 errors

conflicting decleration 'std::istream theFile'
'theFile' has a previous decleration as 'std::istream theFile'
no match for 'operator>>' 'in theFile >>n' 

while you answer this question try to be more noob specific. here is my code.

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

int main()
{
    int n;
    string name;
    ofstream theFile;
    istream theFile;
    theFile.open("Olive.txt");

while(cin>> n>>name)
{
    theFile<< n<<' '<< name;
}

while(theFile>>n>>name)
{
    cout <<endl<<n<<","<<name;
}

    return 0;
}

Upvotes: 0

Views: 946

Answers (2)

Bogolt
Bogolt

Reputation: 520

Use std::fstream instead. It can read/write file, and does what you need. So you will not have to open file two times, as you will doing ifstream and ofstream.

Upvotes: 1

tune2fs
tune2fs

Reputation: 7705

You have declared two variables with the same type. This is not possible. You should declare two variables for the in and outfile and then open the same file:

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

int main()
{
    int n;
    string name;
    ofstream theFileOut;
    ifstream theFileIn;
    theFileOut.open("Olive.txt");

while(cin>> n>>name)
{
    theFileOut<< n<<' '<< name;

}
theFileOut.close();
theFileIn.open("Olive.txt");
while(theFileIn>>n>>name)
{
    cout <<endl<<n<<","<<name;
}

    return 0;
}

Upvotes: 1

Related Questions