0

我有一个很长的 .txt 文件,我想使用 .txt 流式传输getline。我想输入整个文本文档,然后通过一个程序运行它。

然后,我想使用不同的值通过相同的过程运行该新字符串,依此类推 2 次。

到目前为止我有

#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.

我在通过一个过程运行整个文件时遇到了麻烦。我将如何使用getline.

我试过getline, infile.fail, npos, 等等。

4

1 回答 1

1

而不是这个:

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

你可能想要这个:

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

除非我误解了你,你想先阅读整个文件,然后调用flagand cut. 在这种情况下,您需要附加您读取的字符串:

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);

请注意,它会getline覆盖您传递给它的字符串。

此外,while (!input.fail())这是一种不好的循环条件。可能会发生没有更多可用输入但流仍不处于失败状态的情况。在这种情况下,最后一次迭代将处理无效输入。

于 2013-03-12T20:32:40.450 回答