如何对文件中的连续行使用getline

时间:2017-11-01 16:10:48

标签: c++

我试图在文件(未知大小)上使用getline来绘制第一行,将其输入到字符串中,操纵此字符串(替换其他字词,移动一些字符串)并将操纵的行输出回文件。

在此之后,我需要对第2,3行等做同样的事情,直到文件结束。我该怎么做呢?我认为getline的while循环可以工作,但不确定如何获取while循环的条件或如何单独操作每一行。例如第1行和第3行必须与第2行和第4行不同地操作。等等。

我正在尝试做什么的粗略想法:

void readFile(string filename, string text)
{
  ifstream infile;

  infile.open(filename);

  getline(cin, text) // pretty sure this is wrong..

  infile.close(); // close here, or after manipulation???

}

void swapText(string filename, string text)
{

  string decrypText;

  //Manupulate several things..

  return decrypText;

}

void writeToFile(string filename, string decrypText)
{

  ofstream outfile;

  outfile.open(filename);

  outfile << decrypText << endl;

  outfile.close();

}

2 个答案:

答案 0 :(得分:1)

从文件中读取文本行并存储它们的标准习惯用语是:

std::vector<std::string> file_data;
std::string text_line;
while (std::getline(my_data_file, text_line))
{
    // Optional: store the text line
    file_data.push_back(text_line);

    // Call a function to process (or ignore) the text line:
    Process_Text_Line(text_line);
}

如果你想拥有一个读取文件的函数,你可能需要传递vector:

void Read_File(std::vector<std::string>& file_data)
{
    //...
    // Read the data, see "while" loop above.
}

答案 1 :(得分:-1)

每次阅读都不要打开和关闭文件。保持打开并一次读一行:

std::istream in("filein.txt");
std::ostream out("fileout.txt");
std::string line;
while (std::getline(in, line)) {
    // modify line as appropriate
    out << line << '\n';
}