JC2112
JC2112

Reputation: 77

Reading file line by line, and storing as a string

In this program, I'm supposed to read the program line by line, and then use some functions that were given to me that will extract a portion of the string and send it to another function. I'm having a problem with reading the file and 'storing' th

void histogram(const int MaxPages, istream& input, ostream& output)
{
CountedLocation *array[MaxPages];
int linenum = 0;

string temp;
//getline(input, linestring);
//output << linestring;
while (linenum < MaxPages)
{
   string linestring = "";
   getline(input, linestring);
   //linenum++;
   extractTheRequest(linestring);
   if (isAGet(linestring) == true)
   {
       extractLocator(linestring);
       linenum++;
       output << linestring << endl;
       output << "test1";
   }
   linenum++;
}

The problem seems to be that the program never really "reads" the file. I tried having linestring initialized right below the initializion of string temp, as "string linestring = "f" ". The program would of course output the text file as several 'f's strung together. I tried looking on how to read it line by line, but the majority do not use istream, and I am not allowed to edit anything outside of the histogram function. Nothing in the if statement regarding "isAGet" ever really 'occurs'.

My problem is; how do I read the text file line by line, and then store each line into a string? I thought maybe I could just do it in a loop like I have below, storing the line into a temporary stream, doing what I need with it, and then clearing the stream to repeat the process. Is there another approach that would be easier? I can't figure it out on my own.

Upvotes: 1

Views: 1007

Answers (2)

polkovnikov.ph
polkovnikov.ph

Reputation: 6632

The code should look like this:

void histogram(const int MaxPages, istream& input, ostream& output) {
    if (!input.good()) {
        cerr << "File doesn't exist" << endl;
        return;
    }

    string line;
    for (int line_no = 0; getline(input, line); ++line_no) {
        output << '"' << line << '"' << endl;
    }
}

Mention those quotes put to console. They're to show that in case your file has an empty last line, getline will return an error, and work_with_that_line won't get called. It's a wide known problem with getline-style file input. In case you care, consider using char-by-char or binary input.

Upvotes: 1

P0W
P0W

Reputation: 47794

Not sure what your isAGet and extractTheRequest does but to answer "how do I read the text file line by line, and then store each line into a string"

Why not simply this ?

std::vector<std::string> vec;
while ( std::getline(input, linestring) && (linenum < MaxPages ) )
{
  //...
  //Store into std::vector, if required
  vec.push_back(linestring); 

  //.. use other calls 
  output << linestring ;
  linenum++;
}

Upvotes: 1

Related Questions