?
Solved

c++ ifstream file input string help

Posted on 2011-10-13
10
Medium Priority
?
520 Views
Last Modified: 2012-05-12
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

0
Comment
Question by:businessesatoz
  • 5
  • 4
10 Comments
 
LVL 35

Expert Comment

by:sarabande
ID: 36961124
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
 
LVL 7

Accepted Solution

by:
Rahul_Gade earned 750 total points
ID: 36961149
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
 
LVL 35

Expert Comment

by:sarabande
ID: 36961228
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 35

Expert Comment

by:sarabande
ID: 36961251
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
 

Author Comment

by:businessesatoz
ID: 36963118
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
 
LVL 35

Assisted Solution

by:sarabande
sarabande earned 750 total points
ID: 36963274
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
 

Author Comment

by:businessesatoz
ID: 36963286
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
 

Author Comment

by:businessesatoz
ID: 36963295
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
 

Author Closing Comment

by:businessesatoz
ID: 36963332
thanks guys /gals :)
0
 
LVL 35

Expert Comment

by:sarabande
ID: 36963597
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question