【问题标题】:Continuously input lines using getline to end of txt document C++使用getline连续输入行到txt文档C ++的末尾
【发布时间】:2013-03-12 20:28:40
【问题描述】:

我有一个非常长的 .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 将其流式传输。

我试过getlineinfile.failnpos

【问题讨论】:

  • 删除return 声明。
  • @AlexChamberlain:为什么?! return 不在 loop 内。
  • @MM。这就是为什么您应该始终使用{}
  • @AlexChamberlain:是的,最好使用 {} 并缩进代码,但删除 return 是无关紧要的。
  • @MM。是的,但这就是我误读的原因。

标签: c++ input getline


【解决方案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);
}

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

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()) 是一种糟糕的循环条件。可能会发生没有更多可用输入但流仍不处于失败状态的情况。在这种情况下,最后一次迭代将处理无效输入。

【讨论】:

  • 您的第一个解决方案是否会一次读取一行,并在每个过程中运行它?
  • @user2162690 是的,完全正确。
  • 我应该通过第一个过程运行整个 .txt 文件,然后通过第二个过程运行它,依此类推。这是你的第二个案例吗?
  • 是的。您的代码的问题在于它不保存文件,它只是逐行读取它,每次迭代都会覆盖flow,最终只剩下最后一行。
  • 啊,是的,我明白了,有道理
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 2021-11-13
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
相关资源
最近更新 更多