c++ ifstream file input string help

I'm writing a program that will ask the user for the amount of time that they would like to see the file called "data.txt" displayed to the screen.. after getting the number of times to display data.txt from the user, i want to open it for reading and display the amount of time.. i'm stuck i get the amount of time and it only shows up one time.. also i want to put all this in a function called "DispFile" i have wrote what i have done so far below not sure what my errors is. the file data.txt contains the following "Here's Sulky Sue,

What shall we do?

Turn her face to the wall

Till she comes to."

so for example if user wants to see it 3 times it should display

*** Display #1:

Here's Sulky Sue,

What shall we do?

Turn her face to the wall

Till she comes to.




*** Display #2:

Here's Sulky Sue,

What shall we do?

Turn her face to the wall

Till she comes to.




*** Display #3:

Here's Sulky Sue,

What shall we do?

Turn her face to the wall

Till she comes to."

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;
string DispFile (ifstream &read);

int main(void)
{
	int how_many;
	cout <<"how many times would you like to see data.txt? ";
	cin >> how_many;

	ifstream in_stream;
	string mycatchstring;
	in_stream.open("data.txt");
	if(in_stream.fail())
	{
		cout <<"input file opening failed.";
		exit(1);
	}

DispFile(in_stream);


}


string DispFile (ifstream &read)
{
 string strings;
while(!read.eof())
	{
		getline (read,strings );
		cout<<strings <<endl;
	}
return strings;
}

Open in new window

businessesatozAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sarabandeCommented:
you best read the file once into an array. then you can display the contents in a loop as many time the user wants.

change interface of string DispFile(ifstream & read) into

void ReadFile(ifstream & read, std::vector<std::string> &  contents);

Open in new window


then change cout<<strings statement to contents.push_back(strings); what would add the current line to the vector.

you can output the vector in the main function for example by a for loop

for (size_t i = 0; i < contents.size(); ++i)

Open in new window


where you output contents[ i] in the loop block.

Sara
0
Rahul GadeSr. ArchitectCommented:
Does this help?


#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;
void DispFile (ifstream &read);

void DispFile (ifstream &read)
{
      int length;
      char *buffer;

        read.seekg (0, ios::end);
        length = read.tellg();
        read.seekg (0, ios::beg);

        // allocate memory:
        buffer = new char [length];

        memset(buffer,0,length+1);

        // read data as a block:
        read.read (buffer,length);
        
        cout<<buffer<<endl;
}

int main(void)
{
      int how_many;
      cout <<"how many times would you like to see data.txt? ";
      cin >> how_many;

      ifstream *in_stream = new ifstream();
      in_stream->open("data.txt",ios::binary);

      if(in_stream->fail())
      {
            cout <<"input file opening failed.";
            exit(1);
      }

      in_stream->seekg(0,ios_base::beg);

      for(int i = 0; i<how_many; ++i)
      {
            cout<<"Attempt #"<<i+1<<endl;
            DispFile(*in_stream);
      }

      in_stream->close();
      
      getchar();
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sarabandeCommented:
Rahul Gade, the question likely is caused by an academical assignment. if so, ee experts should not post full code samples. generally, ee experts would not do the whole work for a questioner but would help only.

also your code has not a good design as it unnecessarily reads the same file multiple times.

Sara
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

sarabandeCommented:
businessesatoz, alternatively to using a vector you also could collect all lines of the text file into the return string.

then you would print out the returned string in main function in a loop.

to do so, you need two strings in DispFile. the one which is to contain all text with the linefeed characters. and a string which would take the current textline when you call getline(...).

to concatenate strings you simply would use the += operator like

strings += textline + "\n";

Open in new window


Sara
0
businessesatozAuthor Commented:
My goal is to do it this way, One way is to close the file, then reopen it. If you do that, then the file stream's “read” pointer will be reset to point to the very beginning of the stream. Thus, you'll be able to pass the stream object to the DispFile function as many times as you wish... although don't know how to do that.
0
sarabandeCommented:
what you mean by 'this way' ?

close and reopen the file is neither good programming nor recommendable cause a filestream should not be used for multiple opens (it has already set status flags which you would need to reset). waht you can do is to declare the filestream in the DispFile and not pass it from main. that way you can call the DispFile as often as you want and it always would open a new filestream. that is still bad style but better than reusing the filestream.

i strongly recommend to either using a vector or do the concatenation of a multi-line string once in DispFile as suggested. probably the function should be renamed to ReadFile and you don't need to pass the opened ifstream but better the filename as string but that is final doing if all works.

Sara
0
businessesatozAuthor Commented:
the reason being is the book that i'm using is telling me to do it this way to make me get a better understanding.. can you provide an example sara? thanks i do understand your point of view.
0
businessesatozAuthor Commented:
I cannot use anything else besides what i know, i have not learned vectors yet.. so that's why i wanted to follow ", One way is to close the file, then reopen it. If you do that, then the file stream's “read” pointer will be reset to point to the very beginning of the stream. Thus, you'll be able to pass the stream object to the DispFile function as many times as you wish... although don't know how to do that." this way
0
businessesatozAuthor Commented:
thanks guys /gals :)
0
sarabandeCommented:
as told it is much better to have the

std::ifstream instream(filename.c_str());

Open in new window


in the DispFile and pass the filename as const std::string &  from main.

that way you can spare the open and always have a new filestream when calling DispFile.

of course the close must then moved to DispFile as well.

Sara
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.