我有一个非常长的 .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
等
最佳答案
取而代之的是:
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);
}
除非我误解了你,你想先读取整个文件,然后调用 flag
和 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())
是一种糟糕的循环条件形式。可能会发生没有更多可用输入但流仍未处于失败状态的情况。在那种情况下,最后一次迭代将处理无效输入。
关于c++ - 使用getline连续输入行到txt文档的结尾C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15371463/