0

I have a really long .txt file which I want to stream in using getline. I want to input this entire text document, and then run it through a procedure.

I then want to run that new string through the same procedure using a different values, and so on 2 more times.

So far I have

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

using namespace std;

void flag(string & line, int len);
void cut(string & line, int numb);

int main()
{
    string flow;
    ifstream input;
    ofstream output;
    input.open(filename.c_str()); //filename ...

    output.open("flow.txt");

    while (!input.fail())
        getline(input, flow);
    flag(flow, 10);
    flag(flow, 20);
    cut(flow, 20);
    cut(flow, 3);

    output << flow;

    return 10;
}
//procedures are defined below.

I am having troubles running the entire file through a procedure. How would I stream this in, using getline.

I have tried getline, infile.fail, npos, etc.

masoud
  • 55,379
  • 16
  • 141
  • 208

1 Answers1

1

Instead of this:

while(!input.fail())
getline(input, flow);
flag(flow, 10); 
flag(flow, 20); 
cut(flow, 20);
cut(flow, 3);

you probably want this:

while(getline(input, flow)) {
    flag(flow, 10); 
    flag(flow, 20); 
    cut(flow, 20);
    cut(flow, 3);
}

Unless I misunderstood you and you want first read the entire file and then call flag and cut. In that case, you need to append the strings you read:

string data;
while(getline(input, flow))  data += flow + '\n'; // add the newline character
                                                  // because getline doesn't save them

flag(data, 10); 
flag(data, 20); 
cut(data, 20);
cut(data, 3);

Note that getline overwrites the string you pass to it.

Also, while (!input.fail()) is a bad form of loop condition. It might happen that there isn't any more input avaliable but the stream still isn't in a fail state. In that case the last iteration would process invalid input.

jrok
  • 54,456
  • 9
  • 109
  • 141
  • Would your first solution read one line at a time, and run it through each procedure as it goes along? – user2162690 Mar 12 '13 at 20:38
  • @user2162690 Yes, exactly. – jrok Mar 12 '13 at 20:38
  • I am supposed to run the entire .txt file through the first procedure, then run that through the second procedure, and so on. Is that your second case? – user2162690 Mar 12 '13 at 20:41
  • Yes. The problem with your code is that it doesn't save the file, it just reads it line by line, overwrites `flow` each iteration and eventualy leaves you with just the last line. – jrok Mar 12 '13 at 20:44