I'm trying to read from a text file multiple times but I only seem to be able to read the data once. Any advice would be greatly appreciated.

string input;
    
    while (!ifile.eof())
    {
        getline(ifile,input);
        cout << input << endl;
    }
    
    while (!ifile.eof())
    {
        ifile.get(ch);
        cout << ch;
    }

Recommended Answers

All 4 Replies

string input;
 
    while (!ifile.eof())
    {
        getline(ifile,input);
        cout << input << endl;
    }

    ifile.seekg(0,std::ios::beg); //reset read pos to beginning
    ifile.clear(); //clear eofbit

    while (!ifile.eof())
    {
        ifile.get(ch);
        cout << ch;
    }

Thanks for the help. I had tried repositioning the buffer but I didn't reset the eof bit. Thanks again

Member Avatar for Ayu1004

omg thank you so much, this helped me a lot!! thank you!!! ;D

noxee maybe you did something else wrong? well this is my code and the program works! it's nothing special, just a simple code....

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

void characters (ifstream &entrance)
{
	entrance.open ("bla2.txt");
	char a;
	int counter=0;
	entrance>>a;
	while (!entrance.eof())
	{	
		cout<<a<<" ";
		counter++;
		entrance>>a;
	}
	cout<<endl;
	cout<<"There is "<<counter<<" characters in the file"<<endl;
	entrance.close();
}

void words (ifstream &entrance)
{
	entrance.open ("bla2.txt");
	char a[20];
	int counter=0;

	while (!entrance.eof())
	{
		entrance>>a;
		cout<<a<<endl;
		counter++;
	}

	cout<<"There is "<<counter<<" words in the file"<<endl;
	entrance.close();
}

void rows (ifstream &entrance)
{
	entrance.open ("bla2.txt");
	
	char a[100];
	int counter=0;
	while (!entrance.eof())
	{
		entrance.getline (a, sizeof(a));
		counter++;
		cout<<a<<endl;
	}

	cout<<"There is "<<counter<<" rows in the file"<<endl;
	entrance.close();
}

int main () {

	ifstream entrance;
	
	characters (entrance);
	cout<<endl;
	
	entrance.seekg(0,std::ios::beg);
            entrance.clear();
	words (entrance);
	cout<<endl;
	
	entrance.seekg(0,std::ios::beg);
            entrance.clear();
	rows (entrance);
	cout<<endl;

	return 0;
}
commented: two years too late. -7
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.