[英]Continuously input lines using getline to end of txt document C++
我有一個非常長的.txt文件,我想使用getline
將其流式傳輸。 我要輸入整個文本文檔,然后通過一個過程運行它。
然后,我想使用不同的值通過同一過程運行該新字符串,以此類推兩次。
到目前為止,我有
#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())
是循環條件的一種壞形式。 可能發生的情況是不再有可用的輸入,但是流仍然沒有處於失敗狀態。 在這種情況下,最后一次迭代將處理無效的輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.