gpt4 book ai didi

C++ 文本解码器只从文本文件中提取一行

转载 作者:行者123 更新时间:2023-11-28 01:01:25 25 4
gpt4 key购买 nike

我正在开发一个由两部分组成的程序,该程序使用编码器对文本文件进行编码,然后使用解码器对文本文件进行解码。但是我无法让我的解码器读取整个文本文件,它只读取第一行。我该如何解决这个问题,我玩过循环,但它对我没有帮助。

#include <fstream> 
#include <iostream>
#include <string>
using namespace std;

int main()
{
ifstream fin;
ofstream fout;
string lineFromFile;
fin.open("secret.txt");
if (!fin.good()) throw "I/O error";
fout.open("secret.txt", ios::app);
if (!fout.good()) throw "I/O error";

while (fin.good())
{
getline(fin, lineFromFile);
for (int i = 0; i < lineFromFile.length(); i++) // for each char in the string...
lineFromFile[i]--; // bump the ASCII code by 1
fout << lineFromFile << endl;
}//while

fin.close();
fout.close();
return 0;
}

最佳答案

您将在第一次迭代中关闭流(即,在读取第一行之后)。 然后您打开输出流以写入第一行。只有然后您才到达 while 循环的末尾,此时 fin.good() 不再为真,因为您关闭了 fin .

循环应该 读取和写入。在循环之前打开,在循环之后关闭。

补充建议:使用适当的缩进,有助于理解控制流。

关于C++ 文本解码器只从文本文件中提取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8500131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com