Domanda

I am trying to read a text file so as to display the information stored in the file. This is the code I wrote:

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

int main() 
{
    ifstream ifile;
    ifile.open("List Of Hospitals.txt",ios::in); 
    while(!ifile.eof())
    {
        cout<<ifile;
    }

    ifile.close();
    return 0;
}

But I am getting an output of 0x28fe74 and this program never terminates. What changes should I make in this code so that I am enable to read the whole file at once or a single line at a time. (Both Acceptable)

È stato utile?

Soluzione

Try using getline. You're not incrementing the file pointer with your version so it will just print the variable and keep going forever.

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

int main() 
{
string line;
ifstream ifile;
ifile.open("List Of Hospitals.txt",ios::in); 
if (ifile.is_open())
  {
    // getline will pull a line at a time here.
    while ( getline (ifile,line) )
    {
      cout << line << '\n';
    }
    ifile.close();
  }

    return 0;
}

Altri suggerimenti

What you are trying to do is to output the while stream object instance, but there are no output overloads that takes a stream as input.

But if you see e.g. this std::ostream::operator<< reference you will see an overload taking an std::basic_streambuf pointer. This overloaded operator will output all from the std::basic_streambuf. You can get a streams std::basic_streambuf pointer with the rdbuf function.

Can be used like

std::ifstream ifile;
ifile.open("List Of Hospitals.txt");
if (ifile)
    std::cout << ifile.rdbuf();

Also note that your loop is discouraged. This is because the eofbit flag is not set until after you try to read from beyond the end of the file. So a loop like yours would iterate once to many.

Copy a file to standard output stream:

ifstream in;
in.open( "List Of Hospitals.txt",ios::in);
std::copy( std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>(),
           std::ostream_iterator<char>( std::cout, ","));

Try like this code: Reading word by word.

#include "stdafx.h"
#include <iostream>  
#include <fstream>
using namespace std;

int main() 
{

ifstream ifile("List Of Hospitals.txt",ios::in);
char temp[20];   // temp[Maximum length of your word]
while(ifile >>temp) {
    cout << temp << " " ;
}
ifile.close();
    return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top